Lui*_*gan 2 javascript unit-testing reactjs jestjs redux
我想测试我的纯组件,所以我这样做:
MyComp.js
export MyComp = props => {
return (
<Wrapper>Content</Wrapper>
)
}
const MyCompConn = connect()(MyComp);
export default MyCompConn;
Run Code Online (Sandbox Code Playgroud)
在哪里<Wrapper>:
export Wrapper = ({children}) => {
return (
<div>{children}</div>
)
}
const WrapperConn = connect()(Wrapper);
export default WrapperConn;
Run Code Online (Sandbox Code Playgroud)
MyComp.test.js
import React from 'react';
import renderer from 'react-test-renderer';
import { MyComp } from '../../MyComp';
describe('With Snapshot Testing', () => {
it('renders!"', () => {
const component = renderer.create(<Login />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
Run Code Online (Sandbox Code Playgroud)
现在,当我运行时yarn test,我收到此错误:
Invariant Violation: Could not find "store" in either the context or props of "Connect(AppWrapper)". Either wrap the root component in a <Provider> or explicitly pass "store" as a prop to "Connect(AppWrapper)"
发生这种情况是因为<Wrapper>在我的组件中连接<MyComp>,但我不确定如何测试后者,即使它包装在连接的组件上。
为了在不使用模拟存储的情况下测试我们的组件,我们可以使用 Jest 来模拟 React-Redux 本身的连接。PFB 示例:
import React from 'react';
import renderer from 'react-test-renderer';
import { MyComp } from '../../MyComp';
jest.mock('react-redux', () => ({
connect: () => {
return (component) => {
return component
};
}
}));
describe('With Snapshot Testing', () => {
it('renders!"', () => {
const component = renderer.create(<Login />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
Run Code Online (Sandbox Code Playgroud)
现在,这将直接渲染Wrapper组件,而不是connected Wrapper组件。
| 归档时间: |
|
| 查看次数: |
1568 次 |
| 最近记录: |