javascript - 如何在正在测试的组件中模拟 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} />);
解决方案
jest 找不到导入的原因是因为您app
在配置中为文件夹设置了解析器,webpack
但 jest 不知道该解析器。
您可以将app
文件夹添加到modulePaths
jest 配置中https://facebook.github.io/jest/docs/en/webpack.html或使用类似https://www.npmjs.com/package/jest-webpack-resolver自动同步(我自己没有使用过)。
推荐阅读
- html - VBA网页抓取代码错误与宏链接
- javascript - 处理数组以在 React 组件中渲染的最佳方法是什么
- python - 进行迁移后,Django 新属性未显示在管理仪表板中
- javascript - 使用 php、ajax、mysql 删除记录时遇到一些问题
- xamarin.forms - SQLite DB 创建后存储在 Desktop 中的位置
- r - 在参考类中定义字段时的有效性测试错误
- azure - Azure 应用程序网关
- asp.net - asp.net C#中的按钮单击事件错误
- dplyr - 如何使用 NA 值为数据框中的所有列创建汇总函数
- javascript - 显示活跃用户图标——如何确定谁不再在线(寻找 NG 或 JS 解决方案)