reactjs - 检查函数是否在 ReactJS 中触发
问题描述
我的反应应用程序中有这个组件:
export const DEMO = {
test: {
hi: (txt) => console.log(txt)
}
}
export default function App() {
const getAlert = (c) => {
DEMO.test.hi('hello');
}
return (
<div className="App">
<button onClick={getAlert}>open alert</button>
</div>
);
}
it('should trigger calls', () => {
const spyOnFun = jest.spyOn(DEMO.test, 'hi');
const wrapper = shallow(
<App/>,
);
wrapper.find('button').simulate('click');
expect(spyOnFun).toHaveBeenCalledTimes(1); //expect 1 but get 0
});
你怎么能看到我监视了这个方法jest.spyOn(DEMO.test, 'hi');
,我希望在点击后得到 1 个调用,但是我得到了 0 并且我的测试没有通过。
可能是什么问题和锄头要解决?
解决方案
根据您的问题,您可以在对象上使用 spyOn:
// App.js
import React from "react";
import { Button } from "antd";
export const DEMO = {
test: {
hi: (txt) => console.log(txt)
}
};
const info = () => {
DEMO.test.hi("hello");
};
export function App() {
return (
<Button type="primary" onClick={info}>
Display normal message
</Button>
);
}
并为您的测试:
// App.test.js
import React from "react";
import { configure, shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
import { App, DEMO } from "./App";
configure({ adapter: new Adapter() });
it("should trigger calls", () => {
const spy = jest.spyOn(DEMO.test, "hi");
const wrapper = shallow(<App />);
wrapper.find("Button").simulate("click");
expect(spy).toHaveBeenCalledTimes(1);
});
工作演示:https ://codesandbox.io/s/enzyme-spy-on-m3s42
作为建议,React 社区远离了浅层渲染,您应该考虑在您的项目中使用https://testing-library.com/docs/react-testing-library/intro/
推荐阅读
- qooxdoo - qx.event.type.Event.addPromise() 是做什么用的?
- java - 错误:日期/时间值的字符串表示超出范围
- javascript - 如何在没有jQuery的情况下获取回调函数中的行号?
- python - 用 2 个 y 轴绘图仅给出 1 条线
- c++ - 最终输出应该在 [ ] 内,+ = 应该在中间
- python-3.x - Python 导入语句。ModuleNotFoundError:运行测试并引用父文件夹中的模块时
- eclipse - 如何从调试器中删除“无方法返回值”
- javascript - 有没有办法检测为什么 Ajax 调用没有到达 MVC 中的控制器?
- javascript - 关闭时弹出窗口中的垃圾收集javascript
- angular - 如何动态地将 mat-error 添加到 mat-input-field?