如何对React-Redux连接组件进行单元测试?

时间:2016-02-01 13:05:16

标签: unit-testing reactjs mocha sinon redux

我正在使用Mocha,Chai,Karma,Sinon,Webpack进行单元测试。

我按照此链接为React-Redux Code配置了我的测试环境。

https://medium.com/@scbarrus/how-to-get-test-coverage-on-react-with-karma-babel-and-webpack-c9273d805063#.7kcckz73r

我可以成功测试我的动作和reducers javascript代码,但是当涉及到测试我的组件时,它总是会产生一些错误。

import React from 'react';
import TestUtils from 'react/lib/ReactTestUtils'; //I like using the Test Utils, but you can just use the DOM API instead.
import chai from 'chai';
// import sinon from 'sinon';
import spies from 'chai-spies';

chai.use(spies);

let should = chai.should()
  , expect = chai.expect;

import { PhoneVerification } from '../PhoneVerification';

let fakeStore = {
      'isFetching': false,
      'usernameSettings': {
        'errors': {},
        'username': 'sahil',
        'isEditable': false
      },
      'emailSettings': {
        'email': 'test@test.com',
        'isEmailVerified': false,
        'isEditable': false
      },
      'passwordSettings': {
        'errors': {},
        'password': 'showsomestarz',
        'isEditable': false
      },
      'phoneSettings': {
        'isEditable': false,
        'errors': {},
        'otp': null,
        'isOTPSent': false,
        'isOTPReSent': false,
        'isShowMissedCallNumber': false,
        'isShowMissedCallVerificationLink': false,
        'missedCallNumber': null,
        'timeLeftToVerify': null,
        '_verifiedNumber': null,
        'timers': [],
        'phone': '',
        'isPhoneVerified': false
      }
}

function setup () {
    console.log(PhoneVerification);
    // PhoneVerification.componentDidMount = chai.spy();
    let output = TestUtils.renderIntoDocument(<PhoneVerification {...fakeStore}/>);
    return {
        output
    }
}

describe('PhoneVerificationComponent', () => {
    it('should render properly', (done) => {
        const { output } = setup();
        expect(PhoneVerification.prototype.componentDidMount).to.have.been.called;
        done();
    })
});

以上代码出现以下错误。

FAILED TESTS:
  PhoneVerificationComponent
    ✖ should render properly
      Chrome 48.0.2564 (Mac OS X 10.11.3)
    Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

试图从罪人间谍转向chai-spies。

我应该如何对React-Redux连接组件(智能组件)进行单元测试?

5 个答案:

答案 0 :(得分:41)

更好的方法是导出普通组件和连接中包含的组件。命名导出将是组件,默认为包装组件:

export class Sample extends Component {

    render() {
        let { verification } = this.props;
        return (
            <h3>This is my awesome component.</h3>
        );
    }

}

const select = (state) => {
    return {
        verification: state.verification
    }
}

export default connect(select)(Sample);

通过这种方式,您可以在应用中正常导入,但在测试时,您可以使用import { Sample } from 'component'导入指定的导出。

答案 1 :(得分:12)

您可以测试已连接的组件,我认为您应该这样做。您可能希望首先测试未连接的组件,但我建议您在没有测试连接组件的情况下也不会有完整的测试覆盖率。

以下是我对Redux和Enzyme所做的未经测试的摘录。中心思想是使用Provider将测试中的状态连接到测试中的连接组件。

import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';
import SongForm from '../SongForm'; // import the CONNECTED component

// Use the same middlewares you use with Redux's applyMiddleware
const mockStore = configureMockStore([ /* middlewares */ ]);
// Setup the entire state, not just the part Redux passes to the connected component.
const mockStoreInitialized = mockStore({ 
    songs: { 
        songsList: {
            songs: {
                songTags: { /* ... */ } 
            }
        }
    }
}); 

const nullFcn1 = () => null;
const nullFcn2 = () => null;
const nullFcn3 = () => null;

const wrapper = mount( // enzyme
        <Provider store={store}>
          <SongForm
            screen="add"
            disabled={false}
            handleFormSubmit={nullFcn1}
            handleModifySong={nullFcn2}
            handleDeleteSong={nullFcn3}
          />
        </Provider>
      );

const formPropsFromReduxForm = wrapper.find(SongForm).props(); // enzyme
expect(
        formPropsFromReduxForm
      ).to.be.deep.equal({
        screen: 'add',
        songTags: initialSongTags,
        disabled: false,
        handleFormSubmit: nullFcn1,
        handleModifySong: nullFcn2,
        handleDeleteSong: nullFcn3,
      });

===== ../SongForm.js

import React from 'react';
import { connect } from 'react-redux';

const SongForm = (/* object */ props) /* ReactNode */ => {
    /* ... */
    return (
        <form onSubmit={handleSubmit(handleFormSubmit)}>
            ....
        </form>

};

const mapStateToProps = (/* object */ state) /* object */ => ({
    songTags: state.songs.songTags
});
const mapDispatchToProps = () /* object..function */ => ({ /* ... */ });

export default connect(mapStateToProps, mapDispatchToProps)(SongForm)

您可能想要使用纯Redux创建商店。 redux-mock-store只是用于测试的轻量级版本。

您可能想使用react-addons-test-utils而不是airbnb的酶。

我使用airbnb的chai-enzyme来获得React-aware expect选项。在这个例子中不需要它。

答案 2 :(得分:4)

接受答案的问题是我们正在不必要地导出一些东西才能测试它。在我看来,出口课程只是为了测试它不是一个好主意。

这是一个更简洁的解决方案,无需导出除连接组件之外的任何内容:

如果你正在使用jest,你可以模拟connect方法返回三件事:

  1. mapStateToProps
  2. mapDispatchToProps
  3. ReactComponent
  4. 这样做非常简单。有两种方式:内联模拟或全局模拟。

    <强> 1。使用内联模拟

    在测试的描述功能之前添加以下代码段。

    &#13;
    &#13;
    jest.mock('react-redux', () => {
      return {
        connect: (mapStateToProps, mapDispatchToProps) => (ReactComponent) => ({
          mapStateToProps,
          mapDispatchToProps,
          ReactComponent
        }),
        Provider: ({ children }) => children
      }
    })
    &#13;
    &#13;
    &#13;

    <强> 2。使用文件模拟

    1. 在根目录中创建文件__mocks__/react-redux.js(package.json所在的位置)
    2. 在文件中添加以下代码段。
    3. &#13;
      &#13;
      module.exports = {
        connect: (mapStateToProps, mapDispatchToProps) => (ReactComponent) => ({
          mapStateToProps,
          mapDispatchToProps,
          ReactComponent,
        }),
        Provider: ({children}) => children
      };
      &#13;
      &#13;
      &#13;

      模拟后,您可以使用Container.mapStateToPropsContainer.mapDispatchToPropsContainer.ReactComponent访问上述所有三项内容。

      只需执行

      即可导入容器

      import Container from '<path>/<fileName>.container.js'

      希望它有所帮助。

      请注意,如果您使用文件模拟。模拟文件将全局用于所有测试用例(除非您在测试用例之前执行jest.unmock('react-redux'))

      编辑:我写了一篇详细的博客,详细解释了上述内容:

      http://rahulgaba.com/front-end/2018/10/19/unit-testing-redux-containers-the-better-way-using-jest.html

答案 3 :(得分:1)

尝试创建2个文件,一个包含组件本身,不知道任何商店或任何东西(PhoneVerification-component.js)。然后是第二个(PhoneVerification.js),您将在您的应用程序中使用它,它只返回通过connect函数订阅存储的第一个组件,如

import PhoneVerificationComponent from './PhoneVerification-component.js'
import {connect} from 'react-redux'
...
export default connect(mapStateToProps, mapDispatchToProps)(PhoneVerificationComponent)

然后,您可以通过在测试中要求PhoneVerification-component.js并为其提供必要的模拟道具来测试您的“哑”组件。没有经过测试的测试点(连接装饰器,mapStateToProps,mapDispatchToProps等......)

答案 4 :(得分:1)

redux-mock-store 是一个很棒的工具,用于在react中测试redux连接的组件

const containerElement = shallow((<Provider store={store}><ContainerElement /></Provider>));

创建假商店并安装组件

您可以参考本文Testing redux store connected React Components using Jest and Enzyme | TDD | REACT | REACT NATIVE

enter image description here

相关问题