gpt4 book ai didi

reactjs - 如何使用 Jest 监视类属性箭头函数

转载 作者:行者123 更新时间:2023-12-03 13:16:28 25 4
gpt4 key购买 nike

如何使用 Jest 监视类属性箭头函数?我有以下示例测试用例,该用例失败并出现错误预期的模拟函数已被调用。:

import React, {Component} from "react";
import {shallow} from "enzyme";

class App extends Component {
onButtonClick = () => {
// Button click logic.
};

render() {
return <button onClick={this.onButtonClick} />;
}
}

describe("when button is clicked", () => {
it("should call onButtonClick", () => {
const app = shallow(<App />);
const onButtonClickSpy = jest.spyOn(app.instance(), "onButtonClick");

const button = app.find("button");
button.simulate("click");
expect(onButtonClickSpy).toHaveBeenCalled();
});
});

我可以通过将按钮的 onClick 属性更改为 () => this.onButtonClick() 来使测试通过,但不希望仅仅为了更改我的组件实现为了测试。

有什么办法可以在不改变组件实现的情况下让这个测试通过吗?

最佳答案

根据this enzyme issuethis one ,您有两个选择:

<小时/>

选项 1:在 spyOn 之后调用 wrapper.update()

就您而言,这将是:

describe("when button is clicked", () => {
it("should call onButtonClick", () => {
const app = shallow(<App />);
const onButtonClickSpy = jest.spyOn(app.instance(), "onButtonClick");

// This should do the trick
app.update();
app.instance().forceUpdate();

const button = app.find("button");
button.simulate("click");
expect(onButtonClickSpy).toHaveBeenCalled();
});
});
<小时/>

选项 2:不使用类属性

因此,对于您来说,您必须将组件更改为:

class App extends Component {
constructor(props) {
super(props);

this.onButtonClick = this.onButtonClick.bind(this);
}

onButtonClick() {
// Button click logic.
};

render() {
return <button onClick={this.onButtonClick} />;
}
}

关于reactjs - 如何使用 Jest 监视类属性箭头函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52455806/

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