Reputation: 2623
This is a plain TS project. No frameworks.
I have followed through this article here whereby the author mocks the addEventListener
method (on the window however).
I am confused why the mocked function doesn't register as to being called.
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
Simplified implementation:
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();
});
});
Upvotes: 2
Views: 1786
Reputation: 2623
I think the missing step was just to use a spy on the handleClick method, to register that the function was indeed called. The handleClick is still called through, rather than mocking it.
// 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();
});
});
Upvotes: 1
Reputation: 138326
The error indicates that the argument received by toHaveBeenCalled()
(i.e., painter.handleClick
) was expected to be a mock/spy, but it was not.
You could set handleClick
to a mock function in your test:
it('...', () => {
Painter.prototype.handleClick = jest.fn(); // mock handleClick
const painter = new Painter(canvas);
//...
expect(painter.handleClick).toHaveBeenCalled();
})
Upvotes: 0