Foo.jsx
import React from 'react';
export default (props) => {
let {val} = props;
if (val) {
return 'ReactComponentFail';
} else {
return 'ReactComponent';
}
};
Foo.test.js
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Foo from './Foo';
Enzyme.configure({ adapter: new Adapter() });
let wrapper;
describe('foo test', () => {
let props = { val: 0 }
wrapper = shallow(<Foo {...props} />);
test('component test', () => {
expect(wrapper.text()).toEqual('ReactComponent');
});
});
我该如何嘲笑props
?因此,我可以获得100%的代码覆盖率,我们将不胜感激。
我在Google上找不到有关如何模拟道具的任何内容。
答案 0 :(得分:1)
创建模拟的props
并将其传递给SFC。
例如
foo.jsx
:
import React from 'react';
export default (props) => {
let { val } = props;
if (val) {
return 'ReactComponentFail';
} else {
return 'ReactComponent';
}
};
foo.test.jsx
:
import React from 'react';
import { shallow } from 'enzyme';
import Foo from './foo';
describe('foo test', () => {
test('should return ReactComponent', () => {
let props = { val: 0 };
let wrapper = shallow(<Foo {...props} />);
expect(wrapper.text()).toEqual('ReactComponent');
});
test('should return ReactComponentFail', () => {
let props = { val: 1 };
let wrapper = shallow(<Foo {...props} />);
expect(wrapper.text()).toEqual('ReactComponentFail');
});
});
具有100%覆盖率的单元测试结果:
PASS stackoverflow/62694921/foo.test.jsx (10.41s)
foo test
✓ should return ReactComponent (6ms)
✓ should return ReactComponentFail
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
foo.jsx | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 11.845s, estimated 12s