【问题标题】:How pass a test about async method with Jest如何通过 Jest 的异步方法测试
【发布时间】:2021-07-07 13:26:50
【问题描述】:

我尝试编写并运行一个关于异步方法doSomething 的测试,该方法返回Promise<Foo[]>。我将 NestJS 用于后端应用程序。

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

我愿意

test('Test something', () => {
      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);
      });
    }, 5000);

我也尝试了一种更简单的写法

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

无论超时值如何,我都会遇到相同的错误。

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

谁能帮我找到让它工作的方法?

【问题讨论】:

  • 测试代码没有错,除了括号不匹配。一个可能且可能的解释是,一个承诺是未决的,永远不会解决。原因完全取决于您的应用。

标签: typescript testing async-await jestjs nestjs


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2017-04-18
    • 1970-01-01
    相关资源
    最近更新 更多