Typescript 如何用Jest通过异步方法的测试

Typescript 如何用Jest通过异步方法的测试,typescript,testing,async-await,jestjs,nestjs,Typescript,Testing,Async Await,Jestjs,Nestjs,我尝试编写并运行一个关于异步方法doSomething的测试,该方法返回一个Promise。我使用NestJS作为后端应用程序 根据Jest文档,这是可能的,而且似乎相当容易 我知道 我试图用一种更简单的方式来写 test('Test something', async () => { const oldFoo = getFoo(); // type Foo[] const newFoo = getFoo(); const expect = getFoo

我尝试编写并运行一个关于异步方法
doSomething
的测试,该方法返回一个
Promise
。我使用NestJS作为后端应用程序

根据Jest文档,这是可能的,而且似乎相当容易

我知道

我试图用一种更简单的方式来写

test('Test something', async () => {
      const oldFoo = getFoo(); // type Foo[]
      const newFoo = getFoo();
      const expect = getFoo();

      const result = await doSomething(newFoo, oldFoo);

      expect(helper.equal(expect, result)).toEqual(true);
      });
    }, 5000);
我得到了这个错误:

Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout
不管超时值是多少,我都会遇到同样的错误

我的问题:除了测试方法实在太长之外,还有什么解释吗?因为在测试之外(在运行时),该方法相当快


有人能帮我找到让它工作的方法吗?

如果您正在等待承诺,您可能需要异步包装测试,以允许代码在检查结果之前完成

例如,在我的端到端测试中,我会:

it('/api (POST) test to see data returned', async done => {

    const ResponseData = await request(app.getHttpServer())
        .post('/api')
        .set('Accept', 'application/json');

    expect(ResponseData.status).toBe(200);
    done();         // Call this to finish the test
});
我认为在您的测试示例中,您缺少了done()回调函数

test('Test something', async done => {
    const oldFoo = getFoo(); // type Foo[]
    const newFoo = getFoo();
    const expect = getFoo();

    return doSomething(newFoo, oldFoo).then((result) => {
       const cmp: boolean = helper.equal(expect, result);
       expect(cmp).toEqual(true);
    });
    done();
 }

除了不匹配的括号外,测试代码没有任何错误。一个可能的解释是,一个承诺正在等待,而且永远不会解决。原因完全取决于你的应用程序。
test('Test something', async done => {
    const oldFoo = getFoo(); // type Foo[]
    const newFoo = getFoo();
    const expect = getFoo();

    return doSomething(newFoo, oldFoo).then((result) => {
       const cmp: boolean = helper.equal(expect, result);
       expect(cmp).toEqual(true);
    });
    done();
 }