试图用Jest和酶测试我的反应新应用,如下所示。
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import { shallow } from 'enzyme';
import { SignUp } from '../../src/pages';
describe('Testing SignUp component', () => {
it('renders as expected', () => {
const wrapper = shallow(
<SignUp />
);
expect(wrapper).toMatchSnapshot();
});
});
在运行npm test
时,我获得错误Cannot find module 'enzyme/build/ShallowTraversal' from 'shallow.js'
测试套件无法运行。
请注意,测试完成的负酶可以正确运行
test('SignUp Page renders correctly', () => {
const tree = renderer.create(<SignUp />).toJSON();
expect(tree).toMatchSnapshot();
});
可能是什么问题?
刚刚通过安装enzyme-to-json
解决了问题;npm install --save-dev enzyme-to-json
在我的test_file.js
中导入的toJson
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json'; //added this line
将测试更改为此
describe('Testing SignUp component', () => {
it('renders as expected', () => {
const wrapper = shallow(
<SignUp />
);
expect(toJson(wrapper)).toMatchSnapshot(); //edited this line
});
});
更改了package.json中的 snapShotSerializers
"preset": "react-native",
"collectCoverage": true,
"collectCoverageFrom": [
"**/src/**.{js,jsx}"
],
"snapshotSerializers": ["enzyme-to-json/serializer"] //added this line
现在我的测试正常运行。