单元测试 – 如何单元测试React-Redux连接组件?

前端之家收集整理的这篇文章主要介绍了单元测试 – 如何单元测试React-Redux连接组件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用摩卡,Chai,Karma,Sinon,Webpack for Unit测试。

我按照这个链接配置我的React-Redux Code的测试环境。

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

我可以成功地测试我的动作和reducer的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,'passwordSettings': {
        'errors': {},'password': 'showsomestarz','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连接组件(智能组件)?

一个更漂亮的方式来执行此操作,是导出您的普通组件和包装在连接中的组件。命名导出将是组件,默认是包装组件:
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);

这样,您可以在应用程序中正常导入,但是在测试时可以使用导入{Sample}从“组件”导入您的命名导出。

猜你在找的React相关文章