typescript - Jest 和 Typescript 中的 addEventHandler 模拟
问题描述
这是一个普通的 TS 项目。没有框架。
我在这里阅读了这篇文章,作者模拟了该addEventListener
方法(但是在窗口上)。
我很困惑为什么模拟函数没有注册为被调用。
console.log
called in here
at Object.handleClick [as click] (src/painter/painter.ts:24:13)
FAIL src/painter/painter.test.ts
Painter Setup
✕ Should add event handlers to canvas (14 ms)
● Painter Setup › Should add event handlers to canvas
expect(received).toHaveBeenCalled()
Matcher error: received value must be a mock or spy function
简化实现:
class Painter {
constructor(target: HTMLCanvasElement) {
this.canvas = target;
//...
this.init();
}
init() {
this.canvas.addEventListener("click", this.handleClick);
}
// I know that the this context is wrong here, but trying to simplify the issue
handleClick(event: MouseEvent) {
console.log('called in here');
};
}
// testing
const eventListeners: Record<string, Function> = {};
let canvas = document.createElement("canvas");
canvas.addEventListener = jest.fn((eventName: string, callBack: Function) => {
eventListeners[eventName] = callBack;
}) as jest.Mock;
describe("Painter Setup", function () {
it("Should add event handlers to canvas", () => {
const painter = new Painter(canvas);
eventListeners.click({
clientX: 0,
clientY: 0,
});
expect(painter.handleClick).toHaveBeenCalled();
});
});
解决方案
我认为缺少的步骤只是在 handleClick 方法上使用间谍,以注册该函数确实被调用。handleClick 仍然被调用,而不是模拟它。
// testing
const eventListeners: Record<string, Function> = {};
let canvas = document.createElement("canvas");
canvas.addEventListener = jest.fn((eventName: string, callBack: Function) => {
eventListeners[eventName] = callBack;
}) as jest.Mock;
describe("Painter Setup", function () {
it("Should add event handlers to canvas", () => {
const spied = jest.spyOn(Painter.prototype, 'handleClick');
const painter = new Painter(canvas);
// this will still call though the original method. Therefore I will see "called in here" from painter.handleClick
eventListeners.click({
clientX: 0,
clientY: 0,
});
expect(spied).toHaveBeenCalled();
});
});
推荐阅读
- amazon-simple-email-service - 如何使用收件人地址别名发送批量模板电子邮件?
- javascript - 当有一些价值时如何使textarea扩展
- keras - tensorflow-lite tf.lite.Interpreter set_tensor 无法正确识别 uint8 输入张量
- ruby-on-rails - 为什么我在部署到 Heroku 后在浏览器中查看我的应用程序时只看到一个空数组?
- plot - 我可以根据计数结果创建图表吗
- python-3.x - 更改为对数比例,同时在 Seaborn 联合图中的两个轴上移动边缘直方图的垂直比例
- tabulator - 制表符,如何仅更新 1 行的 1 个单元格?
- c# - 循环遍历 GTK# 树视图中节点的子节点
- python - 更改目录时自定义文件不起作用
- javascript - 根据在 .html 键盘中按下的修饰键更改数据键值