【问题标题】:Jasmine spyOn on ReactTestUtils.Simulate.click test is failedReactTestUtils.Simulate.click 上的 Jasmine spyOn 测试失败
【发布时间】:2016-04-19 20:50:25
【问题描述】:

尝试使用 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);
  });

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

【问题讨论】:

    标签: javascript testing reactjs jasmine karma-jasmine


    【解决方案1】:

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

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

    在测试顶部SignIn 组件被导入:

    import SignIn from '../components/SignIn;
    

    只有在那之后,我在 beforeEach 中的 beforeEach 中的 SignIn 已初始化 it 块检查 mock'ed 函数是否被调用,而 SignIn 组件调用到非mock'ed 函数,

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

    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 函数初始化

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2021-12-08
      • 2017-09-15
      • 1970-01-01
      • 2018-04-11
      相关资源
      最近更新 更多