首页 > 解决方案 > 如何在正在测试的组件中模拟 util 函数

问题描述

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

错误:

在此处输入图像描述

我的<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来自 utils/tests的代码。

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} />);

标签: javascriptreactjstestingjestjs

解决方案


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

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


推荐阅读