Redux: How to test a connected component?

前端 未结 3 820
耶瑟儿~
耶瑟儿~ 2020-12-24 03:56

I am using Enzyme to unit test my React components. I understand that in order to test the raw unconnected component I\'d have to just export it and test it (I\

3条回答
  •  误落风尘
    2020-12-24 04:04

    This is an interesting question.

    I usually do import both container and component to do the testing. For container testing I use, redux-mock-store. Component testing is for testing async functions. For instance in your case, login process is an async function using sinon stubs. Here is a snippet of the same,

    import React from 'react';
    import {Provider} from 'react-redux';
    import {mount, shallow} from 'enzyme';
    import {expect} from 'chai';
    import LoginContainer from '../../src/login/login.container';
    import Login from '../../src/login/Login';
    import configureMockStore from 'redux-mock-store';
    import thunk from 'redux-thunk';
    import { stub } from 'sinon';
    
    const mockStore = configureMockStore([thunk]);
    
    describe('Container Login', () => {
      let store;
      beforeEach(() => {
        store = mockStore({
          auth: {
            sport: 'BASKETBALL',
          },
        });
      });
      it('should render the container component', () => {
        const wrapper = mount(
          
            
          
        );
    
        expect(wrapper.find(LoginContainer).length).to.equal(1);
        const container = wrapper.find(LoginContainer);
        expect(container.find(Login).length).to.equal(1);
        expect(container.find(Login).props().auth).to.eql({ sport: 'BASKETBALL' });
      });
    
      it('should perform login', () => {
        const loginStub = stub().withArgs({
          username: 'abcd',
          password: '1234',
        });
        const wrapper = mount();
      wrapper.find('button').simulate('click');
      expect(loginStub.callCount).to.equal(1);
      });
    });
    

提交回复
热议问题