amir
amir

Reputation: 2573

Jest, mongoose and async/await

i have a mongoose model in the node. I want to get all record from that in my test suite with the jest. 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/await. I get 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 I did a mistake? how can I fix this?

Upvotes: 4

Views: 1863

Answers (1)

hurricane
hurricane

Reputation: 6734

You need to add assertions for your async results.

expect.assertions(number) verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.

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 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.',
    });
  });

Upvotes: 3

Related Questions