Jest,mongoose和async / await

问题描述 投票:4回答:1

我在节点中有一个猫鼬模型。我想通过开玩笑从我的测试套件中获取所有记录。这是我的测试:

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);
  });

你可以看到我使用了async / await。我收到以下超时错误:

  ● 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)

我在哪里犯了错误?我怎样才能解决这个问题?

node.js mongodb express mongoose jest
1个回答
3
投票

您需要为异步结果添加断言。

expect.assertions(number)验证在测试期间调用了一定数量的断言。这在测试异步代码时通常很有用,以确保实际调用回调中的断言。

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);
  });

有错误:

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.',
    });
  });
© www.soinside.com 2019 - 2024. All rights reserved.