繁体   English   中英

超过 10000 毫秒的摩卡单元测试超时使用 await Promise.all 时出错

[英]Mocha Unit Test Timeout of 10000ms exceeded Error when using await Promise.all

文件:index.ts // Class 基于默认导出

getItemsA() {
  return Promise.resolve({ // Api Call in real scenario. Mocking here for now.
    success: true;
    result: [{
     itemA: []
    }]
  });
}

getItemsB() {
  return Promise.resolve({ // Api Call in real scenario. Mocking here for now.
    success: true;
    result: [{
     itemB: []
    }]
  });
}

文件服务.ts

import { getItemsA, getItemsB } from 'index.ts';

getService() {
  return new Promise(async (resolve, reject) => {
    const parallelApis = await Promise.all([  // UT Stucks here. Not able to get the parallelApis response.
      getItemsA(), getItemsB()
    ]);

   .... other mapping

   resolve({
      .......
   });
  });
}

文件 test.ts

import items from 'index.ts'; // Class based. Default exported
import service from 'service.ts'; // Class based. Default exported
import { expect } from "chai";
import * as sinon from "sinon";

describe.only("Service", () => {
   let itemAStub;
   let itemBStub;

   beforeEach(() => {
     itemAStub = sinon.stub(items, "getItemsA");
     itemBStub = sinon.stub(items, "getItemsB");

     itemAStub.callsFake(() => {
        return Promise.resolve({
            body: myMock // Dummy
        });
     });

   itemBStub.callsFake(() => {
        return Promise.resolve({
            body: someOtherMock // Dummy
        });
     });
   });

   afterEach(() => {
        itemAStub.restore();
        itemBStub.restore();
   });

   it("Should filter valid gift options", (done) => {
      service.getService().then(res => {
                console.log("RESPONSEEEEEE", res);
                expect(res).to.deep.equal(myMockResponse);
                done();
            })
            .catch(err => {
                console.log("Errorr");
                done(err);
            });
   });
});

当我尝试运行测试用例时,有人可以帮我确定问题吗?我收到以下错误。

Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

我知道延长超时不是解决问题的方法。 存根已创建,但不确定为什么在代码到达 await Promise.all 时会出现超时错误。 如果我删除 done() 那么测试用例会成功,但是 function 没有被执行。 任何帮助将非常感激。

getService返回的 promise 未在发布的代码中得到解决,因此将保持挂起状态并达到时间限制。

由于您在调用new Promise时使用了async function 作为执行程序,因此您可能不需要创建新的 promise

getService() {
    return Promise.all([
      getItemsA(), getItemsB()
    ]);
  });
}

这并没有明确“其他映射”的含义,但请记住, async function 返回一个 promise,该 promise 由async函数的明显返回值解决,或在 asyncZ 主体中被抛出错误如果需要,您可以将getService设为异步 function。

当我们从命令行运行 Mocha 时,它将读取这个具有默认超时的文件。

要更改此时间,您可以使用以下命令重置:

./node_modules/.bin/mocha  --timeout 20000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM