Categories
JavaScript Answers

How to check if function was called with Jest and JavaScript?

Spread the love

To check if function was called with Jest and JavaScript, we create a spy and use the toHaveBeenCalled method.

For instance, we write

const child = require("./child");
const main = require("./add").main;

const spy = jest.spyOn(child, "child");

describe("main", () => {
  it("should call child fn", () => {
    expect(main(1)).toBe(2);
    expect(spy).toHaveBeenCalled();
  });
});

to create a test with it.

We call jest.spyOn in the it test callback to create a spy on the child module’s child function.

Then we call main which calls child.

And then we call expect with spy and toHaveBeenCalled to check if the child function is called.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *