Jest, mongoose and async / are waiting

I have a mongoose model in node. I want to get the whole record from this in my test suite with a joke. here is my test:

test('should find and return all active coupon codes ', async () => {
    const res = await CouponModel.find({ active: true });
    expect(res).toBeDefined();
    const s = res;
    console.log(s);
  });

as you can see i used async / wait. I get the following timeout error:

   coupon code test › should find and return all active coupon codes 

Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

  at node_modules/jest-jasmine2/build/queue_runner.js:64:21
  at ontimeout (timers.js:478:11)
  at tryOnTimeout (timers.js:302:5)
  at Timer.listOnTimeout (timers.js:262:5)

where did i make a mistake? How can i fix this?

+4
source share
1 answer

You need to add statements for your async results.

expect.assertions(number)Verifies that a certain amount of assertion is called during the test. This is often useful when testing asynchronous code to make sure that the statements in the callback actually received the call.

test('should find and return all active coupon codes ', async () => {
    expect.assertions(1);
    const res = await CouponModel.find({ active: true });
    expect(res).toBeDefined();
    const s = res;
    console.log(s);
  });

With an error:

test('should find and return all active coupon codes ', async () => {
    expect.assertions(1);
    try {
        const res = await CouponModel.find({ active: true });
        expect(res).toBeDefined();
    } catch (e) {
        expect(e).toEqual({
        error: 'CouponModel with 1 not found.',
    });
  });
+2
source

Source: https://habr.com/ru/post/1691609/


All Articles