【问题标题】:Jest, mongoose and async/await开玩笑,猫鼬和异步/等待
【发布时间】:2018-06-11 22:57:47
【问题描述】:

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

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)

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

【问题讨论】:

  • 这似乎是一个奇怪的测试,你为什么要测试 mongoose.find 是否在你的代码中工作?像 .find 这样的猫鼬查询也不会返回实际的承诺 (mongoosejs.com/docs/promises.html)

标签: node.js mongodb express mongoose jestjs


【解决方案1】:

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

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

【讨论】:

  • 期望一个断言,但收到零个断言调用。我认为 mongo 和 jest 有问题。因为这段代码在 API 部分运行良好。但不在测试中
  • @amir 对此错误的任何更新,我也面临同样的问题。我在 jest repo github.com/facebook/jest/issues/3045 上解决了这些问题,但无法从中获得太多帮助。
猜你喜欢
  • 1970-01-01
  • 2018-08-30
  • 2019-05-10
  • 2020-10-16
  • 1970-01-01
  • 2023-02-09
  • 2019-12-12
  • 2016-06-22
  • 2018-04-13
相关资源
最近更新 更多