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

时间:2018-05-12 20:28:34

标签: 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
  });
});

来自utils / tests的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} />);

0 个答案:

没有答案