尝试使用Karma+Jasmine测试React组件时,我试图检查是否调用了onClick处理程序中的所有函数,但是测试返回假结果:
`Expected spy reportLoginWithEmail to have been called.`这是我的组成部分:
<a className="sign-in-with-email" onClick={this.signInWithEmail}>
Or Sign in with your Email
</a>signInWithEmail处理程序:
signInWithEmail = (event) => {
event.preventDefault();
this.setState({
isEmailSignIn: true
});
biActions.reportLoginWithEmail();
};测试:
describe('SignIn', () => {
let component, biActions;
beforeEach(() => {
component = TestUtils.renderIntoDocument(<SignIn/>);
biActions = require('../../../actions/BIActions');
spyOn(biActions, 'reportLoginWithEmail');
});
it('test clicking on login by email call function', () => {
let signInEmail = TestUtils.findRenderedDOMComponentWithClass(component, 'sign-in-with-email');
TestUtils.Simulate.click(signInEmail);
expect(biActions.reportLoginWithEmail).toHaveBeenCalled();
});
});另一方面,state更改的测试返回true:
it('test clicking on login by email change state', () => {
let signInEmail = TestUtils.findRenderedDOMComponentWithClass(component, 'sign-in-with-email');
TestUtils.Simulate.click(signInEmail);
expect(component.state.isEmailSignIn).toBe(true);
});我错过了什么,有什么建议吗?
发布于 2016-04-20 18:55:20
好吧,经过几个小时的研究,我发现了这个问题:
组件的require顺序非常重要,这是我的问题。
在测试SignIn组件的顶部导入了:
import SignIn from '../components/SignIn;只有在mock reportLoginWithEmail in beforeEach (已在SignIn组件中初始化)之后,it块才检查是否调用了mock'ed函数,而SignIn组件调用了非mock'ed函数,
因此,通过更改require的顺序并删除测试顶部的import of SignIn组件,解决了这个问题,工作代码:
beforeEach(() => {
biActions = require('../../../actions/BIActions');
spyOn(biActions, 'reportLoginWithEmail');
SignIn = require('../../../components/LoginPage/SignIn');
LoginByEmail = require('../../../components/LoginPage/LoginByEmail');
component = TestUtils.renderIntoDocument(<SignIn/>);
});在这种情况下,SignIn组件由mock'ed reportLoginWithEmail函数初始化
https://stackoverflow.com/questions/36729195
复制相似问题