Jasmine spyOn ReactTestUtils.Simulate.click 测试失败

Jasmine spyOn on ReactTestUtils.Simulate.click test is failed

尝试使用 Karma+Jasmine 测试 React 组件, 我正在尝试检查是否调用了 onClick 处理程序中的所有函数,但测试 return 错误结果:

`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 的测试更改 return 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);
  });

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

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

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

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

import SignIn from '../components/SignIn;

并且仅在那之后我 mock reportLoginWithEmail in 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 组件使用 mockreportLoginWithEmail 函数初始化