我正在使用摩卡,Chai,Karma,Sinon,Webpack for Unit测试。
我按照这个链接配置我的React-Redux Code的测试环境。
我可以成功地测试我的动作和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连接组件(智能组件)?
一个更漂亮的方式来执行此操作,是导出您的普通组件和包装在连接中的组件。命名导出将是组件,默认是包装组件:
原文链接:https://www.f2er.com/react/301885.htmlexport 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}从“组件”导入您的命名导出。