【发布时间】:2020-05-25 02:13:23
【问题描述】:
我正在尝试编写一个使用酶模拟按钮单击的测试,该按钮期望触发 onClick 处理程序。我想用模拟替换组件的 onClick 处理程序。测试运行时,将调用组件类方法而不是模拟函数。任何指导将不胜感激!
下面是测试输出:
FAIL src/Form.test.js
● Console
console.log src/Form.js:5
this is from the component
● Submit handler called on click
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
14 | submitButton.simulate("click");
15 |
> 16 | expect(onHandleSubmitMock).toHaveBeenCalled();
| ^
17 | });
18 |
at Object.<anonymous>.test (src/Form.test.js:16:30)
包版本: “笑话”:25.1.0 “开玩笑酶”:7.1.2 “反应”:16.8.6
Form.js 组件
import React, { Component } from "react";
export class Form extends Component {
onHandleSubmit = () => {
console.log("this is from the component");
};
render() {
return (
<div>
<button data-test="submit" onClick={this.onHandleSubmit}>
Submit
</button>
</div>
);
}
}
export default Form;
Form.test.js
import React from "react";
import { shallow } from "enzyme";
import Form from "./Form";
test("Submit handler called on click", () => {
const onHandleSubmitMock = jest.fn(() => console.log("mock was called"));
const wrapper = shallow(<Form />);
wrapper.instance().onHandleSubmit = onHandleSubmitMock;
wrapper.update();
const submitButton = wrapper.find(`[data-test="submit"]`);
submitButton.simulate("click");
expect(onHandleSubmitMock).toHaveBeenCalled();
});
【问题讨论】:
-
我强烈建议不要模拟你认为你正在测试的东西的一部分。模拟出合作者(在本例中为
console.log)。 -
@jonrsharpe 感谢您的意见。添加了 console.log 是为了弄清楚测试发生了什么。我的意图是测试以确保调用 onHandlerSubmit。那不是合作者吗?
-
不,它是您正在测试的组件的一部分。您应该通过公共 API 进行测试,基本上是道具和渲染的 DOM,而不是通过内部。测试行为,而不是执行。
-
谢谢@jonrsharpe!我仍在努力解决所有这些测试问题。这很有帮助。
标签: reactjs unit-testing mocking jestjs enzyme