问题
Created a simple app using create-react-app
then updated my App.js and added redux/store.
class App extends Component {
render() {
return (
<header className="header">
<h1>todos</h1>
</header>
);
}
}
function mapStateToProps(state) {
return {
data: state.data
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(ActionCreators, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
then trying to test my App on App.test.js using Enzyme and Jest.
import React from 'react'
import Enzyme, { mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16';
import App from './App'
Enzyme.configure({ adapter: new Adapter() });
function setup() {
const props = {
addTodo: jest.fn()
}
const enzymeWrapper = mount(<App {...props} />)
return {
props,
enzymeWrapper
}
}
describe('components', () => {
describe('App', () => {
it('should render self and subcomponents', () => {
const { enzymeWrapper } = setup()
expect(enzymeWrapper.find('header')).toBe(true)
})
})
})
but throwing error: Invariant Violation: Could not find "store" in either the context or props of "Connect(App)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(App)".
Any Ideas?
回答1:
This is happening because you're trying to test the component without a <Provider>
(which would normally make the store available to its sub-components).
What I normally do in this situation is test my component without the Redux connect
binding. To do this, you can export the App
component itself:
export class App extends Component // etc...
and then import that in the test file using the deconstructed assignment syntax:
import { App } from './App'
You can assume (hopefully... ;) ) that Redux and the React bindings have been properly tested by their creators, and spend your time on testing your own code instead.
There's a little more information about this in the Redux docs.
来源:https://stackoverflow.com/questions/49373836/react-jest-enzyme-how-to-pass-test-app-js-with-store-redux