首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >茉莉花spyOn on ReactTestUtils.Simulate.click测试失败

茉莉花spyOn on ReactTestUtils.Simulate.click测试失败
EN

Stack Overflow用户
提问于 2016-04-19 20:50:25
回答 1查看 382关注 0票数 2

尝试使用Karma+Jasmine测试React组件时,我试图检查是否调用了onClick处理程序中的所有函数,但是测试返回假结果:

代码语言:javascript
复制
`Expected spy reportLoginWithEmail to have been called.`

这是我的组成部分:

代码语言:javascript
复制
<a className="sign-in-with-email" onClick={this.signInWithEmail}>
   Or Sign in with your Email
</a>

signInWithEmail处理程序:

代码语言:javascript
复制
signInWithEmail = (event) => {
  event.preventDefault();
  this.setState({
    isEmailSignIn: true
  });
  biActions.reportLoginWithEmail(); 
};

测试:

代码语言:javascript
复制
  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

代码语言:javascript
复制
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);
  });

我错过了什么,有什么建议吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-20 18:55:20

好吧,经过几个小时的研究,我发现了这个问题:

组件的require顺序非常重要,这是我的问题。

在测试SignIn组件的顶部导入了:

代码语言:javascript
复制
import SignIn from '../components/SignIn;

只有在mock reportLoginWithEmail in beforeEach (已在SignIn组件中初始化)之后,it块才检查是否调用了mock'ed函数,而SignIn组件调用了非mock'ed函数,

因此,通过更改require的顺序并删除测试顶部的import of SignIn组件,解决了这个问题,工作代码:

代码语言:javascript
复制
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函数初始化

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36729195

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档