加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:33:29 所属栏目:百科 来源:网络整理
导读:我正在使用摩卡,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 我可以成功地
我正在使用摩卡,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}从“组件”导入您的命名导出。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读