javascript - 如何在被测组件中模拟 util 函数

标签 javascript reactjs testing jestjs

https://github.com/Futuratum/moon.holdings/issues/38

错误:

enter image description here

我的<Square />组件

import React from 'react';

// Utils
import { calculateBalance } from 'utils/math';
import { setStyle } from 'utils/modifiers';

export default coin => (
  <li className="coin-square" style={setStyle(coin.id)}>
    <section>
      <h1>{coin.symbol}</h1>
      <p>Price: ${coin.price_usd}</p>
      <p>Holdings: {coin.balance}</p>
      <p className="f18"> ${calculateBalance(coin)}</p>
    </section>
  </li>
);

测试:

import { testCommonComponentAttrs } from '../../utils/tests';

import Square from './square';

const coin = {
  id: 'bitcoin',
  symbol: 'BTC',
  price_usd: '0',
  balance: '0'
};

const calculateBalance = jest.fn();
const setStyle = jest.fn();

describe('<Square /> component', () => {
  testCommonComponentAttrs(Square, {
    coin,
    setStyle,
    calculateBalance
  });
});

代码 testCommonComponentAttrs来自实用程序/测试。

import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';

/**
 * Automatically tests that the component matches the Jest snapshot.
 * NOTE: If you are receiving a warning like the following in your tests:
 *
 *   Warning: React.createElement: type is invalid -- expected a string...
 *
 * Then you most likely need to pass the appropriate props.
 *
 * @param {!React.Component} Component The React component to wrap and test.
 * @param {!Object} props The (optional) props to use for the basic Jest test.
 */
export const testCommonComponentAttrs = (Component, props) => {
  describe('when rendering', () => {
    const wrapper = shallow(<Component {...props} />);

    it('should render a component matching the snapshot', () => {
      const tree = toJson(wrapper);
      expect(tree).toMatchSnapshot();
      expect(wrapper).toHaveLength(1);
    });
  });
};

export const getComponentWrapper = (Component, props) =>
  shallow(<Component {...props} />);

最佳答案

jest 找不到导入的原因是因为您在 webpack 配置中为 app 文件夹设置了解析器,但 jest 不知道该解析器。

您可以将 app 文件夹添加到 jest 配置中的 modulePaths https://facebook.github.io/jest/docs/en/webpack.html或使用类似 https://www.npmjs.com/package/jest-webpack-resolver 的东西自动同步(我自己没用过)。

关于javascript - 如何在被测组件中模拟 util 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50310422/

相关文章:

javascript - 如何在 Canvas 中画线

javascript - ajax异步删除帖子 - php

javascript - Protractor 剑道组合框

testing - TestNG - 是否可以将 AnnotationTransformer 与 dataProvider 一起使用?

javascript - 正则表达式无法获取版本号

javascript - 揭示模块模式 - 使用 Jasmine 进行单元测试

css - 如何创建自定义单选按钮?

javascript - 我可以将 react-native-i18n 库与 react-native-web-boilerplate 一起使用吗

ruby-on-rails - 将 MomentJS 格式化为 Rails DateTime

c# - Visual Studio 2012 测试类别层次结构(测试资源管理器)