我想测试我的组件是否获得在浅层渲染中传递的道具:
const defaultProps = {
testString: 'string',
testArr: [],
checkData: jest.fn(),
activePage: false,
};
const wrapper = shallow(<Component { ...defaultProps } />);
test("should load component with passed props", () => {
expect(wrapper.props()).toEqual(defaultProps);
});
但出现错误,在控制台中,我看到了测试组件的所有子组件。我正确使用了mount和test pass,但是我想知道为什么浅渲染无法正确通过props?
答案 0 :(得分:0)
这是一个可行的示例,您可以使用.props() => Object访问组件的道具。
index.tsx
:
import React, { Component } from 'react';
class SomeComponent extends Component {
render() {
return <div {...this.props}></div>;
}
}
export default SomeComponent;
index.spec.tsx
:
import React from 'react';
import SomeComponent from './';
import { shallow } from 'enzyme';
describe('SomeComponent', () => {
it('should load component with passed props', () => {
const defaultProps = {
testString: 'string',
testArr: [],
checkData: jest.fn(),
activePage: false
};
const wrapper = shallow(<SomeComponent {...defaultProps}></SomeComponent>);
expect(wrapper.props()).toEqual(defaultProps);
});
});
单元测试结果覆盖率100%
PASS src/stackoverflow/56011077/index.spec.tsx
SomeComponent
✓ should load component with passed props (8ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 5.585s, estimated 11s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/56011077