我想测试我的纯组件,所以我要这样做:
MyComp.js
export MyComp = props => {
return (
<Wrapper>Content</Wrapper>
)
}
const MyCompConn = connect()(MyComp);
export default MyCompConn;
<Wrapper>
处:
export Wrapper = ({children}) => {
return (
<div>{children}</div>
)
}
const WrapperConn = connect()(Wrapper);
export default WrapperConn;
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();
});
});
现在,当我运行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>
组件中,但是我不确定如何测试 just ,即使后者被包装在已连接的组件中组件。
答案 0 :(得分:2)
要在不使用模拟存储的情况下测试组件,我们可以使用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();
});
});
现在,这将直接呈现Wrapper
组件,而不是connected Wrapper
组件。
答案 1 :(得分:0)
尝试一下:
import configureMockStore from 'redux-mock-store';
const store = mockStore({});
const component = renderer.create(<Provider store={store}><Login /></Provider>);