Testing a Redux-connected component using Enzyme

て烟熏妆下的殇ゞ 提交于 2019-12-11 04:27:19

问题


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??


回答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.




回答2:


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);
});


来源:https://stackoverflow.com/questions/49446530/testing-a-redux-connected-component-using-enzyme

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