Jest,mongoose和async / await

时间:2018-01-02 08:05:14

标签: node.js mongodb express mongoose jest

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

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)

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

1 个答案:

答案 0 :(得分: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.',
    });
  });