Как смоделировать функцию util в тестируемом компоненте - PullRequest
0 голосов
/ 12 мая 2018

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

1 Ответ

0 голосов
/ 12 мая 2018

Причина, по которой jest не может найти импорт, заключается в том, что вы установили преобразователь для папки app в конфигурации webpack, но jest не знает об этом преобразователе.

Вы можете добавить папку app к modulePaths в конфигурации jest https://facebook.github.io/jest/docs/en/webpack.html или использовать что-то вроде https://www.npmjs.com/package/jest-webpack-resolver для автоматической синхронизации (не использовал это сам).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...