Test of async method in Jest

An example of code:

module.exports = {
  checkUser: (user, cb) => {
    if (user.age < 18) {
      setTimeout(() => {
        // do smth
        cb(user.age);
      }, 500);
    }
  },
};

If you write test like this:

describe("example", () => {
  it("First test", () => {
    expect.hasAssertions(); // it checks that at least one "expect" was called

    const user = {
      age: 10,
    };

    checkUser(user, (age) => {
      expect(age).toBe(user.age);
    });
  });
});

This test will fail

To make this test passed you should use callback function in method it or use Promise

describe("example", () => {
  it("First test", (done) => {
    expect.hasAssertions();

    const user = {
      age: 10,
    };

    checkUser(user, (age) => {
      expect(age).toBe(user.age);
      done();
    });
  });
});
Share:

About

My name is Max, also known as @mxkvl.

I am a software developer, currently working mostly with TypeScript, React and Node ecosystems.

I write a blog about topics that interest me most: programming languages in general, TypeScript, testing, writing and other great stuff.

Join the Mailing List