React, Jest, Enzyme how to pass test App.js with store redux

淺唱寂寞╮ 提交于 2019-12-23 11:59:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!