Test of async method in Jest

An example of code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
module.exports = {
  checkUser: (user, cb) => {
    if (user.age < 18) {
      setTimeout(() => {
        // do smth
        cb(user.age);
      }, 500);
    }
  },
};

If you write test like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
describe("example", () => {
  it("First test", (done) => {
    expect.hasAssertions();

    const user = {
      age: 10,
    };

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

Subscribe to the newsletter

Get a once-per-week email with my latest content. By subscribing to this newsletter you will also be the first to receive last updates of my eBooks and courses.

0 members

Comments 💬