簡體   English   中英

addEventHandler mocking in Jest & Typescript

[英]addEventHandler mocking in Jest & Typescript

這是一個普通的 TS 項目。 沒有框架。

在這里閱讀了這篇文章,作者模擬了addEventListener方法(但是在 window 上)。

我很困惑為什么嘲笑的 function 沒有注冊為被調用。

 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 方法上使用間諜,以注冊確實調用了 function。 handleClick 仍然是通過調用的,而不是 mocking 它。

// 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(); 
  });
});

該錯誤表明toHaveBeenCalled()收到的參數(即, painter.handleClick )應該是一個模擬/間諜,但它不是。

您可以在測試中將handleClick設置為模擬 function :

it('...', () => {
  Painter.prototype.handleClick = jest.fn(); // mock handleClick
  const painter = new Painter(canvas);

  //...
  expect(painter.handleClick).toHaveBeenCalled();
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM