6

have problem with testing redux connected component with enzyme

import React from 'react'
import { shallow, mount, render } from 'enzyme'
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
import Login from '../../src/routes/login/components/Login'

configure({ adapter: new Adapter() })

describe('<Login />', () => {
    test('component has form-group nodes', () => {
        const component = shallow(<Login />).dive()
        expect(component.find('.form-group')).to.have.length(2)
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

But have error in console - Invariant Violation: Could not find "store" in either the context or props of "Connect(Login)".

how to deal with it??

Dmytro P
  • 61
  • 1
  • 4
  • Possible duplicate of [React, Jest, Enzyme how to pass test App.js with store redux](https://stackoverflow.com/questions/49373836/react-jest-enzyme-how-to-pass-test-app-js-with-store-redux) – Andrew Miroshnichenko Mar 23 '18 at 16:51
  • Possible duplicate of [How to Unit Test React-Redux Connected Components?](https://stackoverflow.com/questions/35131312/how-to-unit-test-react-redux-connected-components) – Andrea Carraro Mar 25 '18 at 21:12
  • You have to mock store if you want to test connected components. But you should not do that, test the component itself instead. – Moyote Mar 26 '18 at 18:24

2 Answers2

6

I faced a similar problem and I managed to solve it by using redux-mock-store for my store mocking and I used mount instead of shallow to reach my connected component with redux like that:

import React, { Component } from 'react';
import { mount } from 'enzyme';
import { expect } from 'chai';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import App from '../../src/App';

it('renders without crashing', () => {

  const mockStore = configureStore();
  const initialState = {
    someState: [],
    someReducer: {},
  };

  const store = mockStore(initialState);

  const wrapper = mount(
    <Provider store={store}>
      <App />
    </Provider>
  );

  console.log(wrapper.debug())

  expect(wrapper.find('.app-container')).to.have.lengthOf(1);
});
Muho
  • 3,188
  • 23
  • 34
1

Have a read this best practice from [redux doc][1] https://github.com/reduxjs/redux/blob/master/docs/recipes/WritingTests.md#connected-components

The issue you have encountered is because you are testing the connected component, what you should be doing is like what the official doc suggested:

export class Login extends Component { /* ... */ }

export default connect(mapStateToProps)(Login )

Instead of unit testing the connected component, you can simply unit test the Login component which you won't need to mock the store etc.

Hope it helps.

schrodinger's code
  • 2,624
  • 1
  • 25
  • 19