gpt4 book ai didi

javascript - ReactTestUtils.Simulate.click 测试上的 Jasmine spyOn 失败

转载 作者:行者123 更新时间:2023-11-30 00:10:24 27 4
gpt4 key购买 nike

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

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

最佳答案

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

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

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

import SignIn from '../components/SignIn;

只有在那之后,我才在 beforeEachmock reportLoginWithEmail 已经在 SignIn 组件中初始化,it block 检查是否在 SignIn 组件调用非 mocked 函数时调用了 mocked 函数,

因此,通过更改 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 函数初始化

关于javascript - ReactTestUtils.Simulate.click 测试上的 Jasmine spyOn 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36729195/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com