关于ReactTestUtils.Simulate.click的Jasmine spyOn测试失败

时间:2016-04-19 20:50:25

标签: javascript testing reactjs jasmine karma-jasmine

尝试使用Karma + Jasmine测试React组件, 我试图检查调用所有函数到 <StackPanel Orientation="Horizontal"> <Button Width="100" Content="Foo" Click="Button_Click"/> <Button Width="100" Content="Bar" Click="Button_Click"/> <Button Width="100" Content="Baz" Click="Button_Click"/> </StackPanel> <!-- set the width to 300 --> <ListBox Grid.Row="1" Name="TheList" Height="100" Width="300" /> 处理程序,但测试返回false结果:

onClick

这是我的组件:

`Expected spy reportLoginWithEmail to have been called.`

signInWithEmail处理程序:

<a className="sign-in-with-email" onClick={this.signInWithEmail}>
   Or Sign in with your Email
</a>

测试:

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

我缺少什么,有什么建议吗?

1 个答案:

答案 0 :(得分:1)

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

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

导入测试SignIn组件的顶部:

import SignIn from '../components/SignIn;

并且仅在mockreportLoginWithEmail组件已初始化的beforeEach SignIn之后,it阻止检查mock是否为SignInmock组件调用非require'ed函数

时调用了ed函数

因此问题已通过import的更改顺序得到解决,并在测试,工作代码顶部删除了SignInbeforeEach(() => { 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函数初始化 JPanel panelGraph = new JPanel(); panelGraph.setBounds(220, 64, 329, 250); panelMain.add(panelGraph); //it is inside the main panel panelGraph.setLayout(null); 组件