问题
We use Enzyme and Jest for testing. Updated to the latest version of react-redux in our code base, and all of the connected component test cases started failing (Version 6). Using
import { createMockStore } from 'redux-test-utils';
to create store
Test cases that worked with older version:
const wrapper = shallow(<SomeConnectedComponent />, {context: { store }});
This fails giving error
Invariant Violation: Could not find "store" in the context of "Connect(SomeConnectedComponent )".
Reading few posts, got a suggestion to mount and wrap with provider wrapper
const wrapper = mount(<Provider store={store}><SomeConnectedComponent /></Provider>);
Above code works, but I want it to work with swallow for unit testing.
Edit :
const wrapper = shallow(<Provider store={store}>
<SomeConnectedComponent />
</Provider>)
Above code returns empty shallowWraper object.
What is the best way to swallow connected component with react-redux version > 6
回答1:
Shallow does not work with the latest version of react-redux. From Version 6.x, it causes the mentioned problem.
The best solution I found was to use a older version of react-redux for testing, and the newer one for actual code.
1) Add the older version as a dev dependency. Because a newer version of react-redux is there you will need to use a alias. This can be any version 5.x This will install "react-redux-test"
yarn add react-redux-test@npm:react-redux@5.0.6 -D
2) Under the _ mocks _ folder, create a new file react-redux.js and export the older version from within
export * from 'react-redux-test';
This mock will be used in every test case file by default, so the old testing code no longer breaks.
If however you want to test with the new react-redux library, you can use
jest.unmock('react-redux')
above the new test file.
After upgrading there were hundreds of tests failing, this approach works for me as i want to use the Hooks Api in new components as well.
This way you can use features the new library until enzyme / react-redux come up with a fix.
来源:https://stackoverflow.com/questions/59191129/enzyme-jest-react-testing-shallow-connected-component-with-react-redux-6