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

How to Unit Test React-Redux Connected Components?

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

我按照这个 link 配置我的 React-Redux 代码测试环境。

How to implement testing + code coverage on React with Karma, Babel, and Webpack

我可以成功测试我的 action 和 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.

尝试从 sinon 间谍切换到 chai-spies。

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

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

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

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

一个更漂亮的方法是导出普通组件和包含在 connect 中的组件。命名导出将是组件,默认是包装组件:

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'.

导入您的命名导出

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

以下是我使用 Redux 和 Enzyme 所做的未经测试的摘录。中心思想是通过Provider将test中的state连接到test中的connected component

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 的 Enzyme。

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

已接受答案的问题是我们不必要地导出某些东西只是为了能够对其进行测试。在我看来,导出 class 只是为了测试它并不是一个好主意。

这是一个更简洁的解决方案,除了连接的组件外不需要导出任何东西:

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

  1. mapStateToProps
  2. mapDispatchToProps
  3. 反应组件

这样做非常简单。有两种方法:内联模拟或全局模拟。

1.使用内联模拟

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

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

2。使用文件 mock

  1. 在根目录(package.json 所在的位置)创建一个文件__mocks__/react-redux.js
  2. 在文件中添加以下代码段。

module.exports = {
  connect: (mapStateToProps, mapDispatchToProps) => (ReactComponent) => ({
    mapStateToProps,
    mapDispatchToProps,
    ReactComponent,
  }),
  Provider: ({children}) => children
};

模拟后,您将能够使用 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

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