【发布时间】:2016-05-09 22:48:19
【问题描述】:
我正在使用 Mocha、Chai、Karma、Sinon、Webpack 进行单元测试。
我点击此链接为 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 间谍。
我应该如何对我的 React-Redux 连接组件(智能组件)进行单元测试?
【问题讨论】:
-
如何导出组件?您是使用命名导出还是仅使用导出默认值?
import { PhoneVerification } from '../PhoneVerification';是您的违规行,当您这样做时,如果您没有进行命名导出,则会得到未定义。 -
我正在使用命名导出。
-
我也有类似的设置并且收到类似的错误消息。这方面有进展吗?谢谢。
-
能不能在这段代码sn-p中加js让代码高亮?
标签: unit-testing reactjs mocha.js sinon redux