测试函数不能同时接受“完成”回调

mon*_*ser 35 javascript unit-testing jestjs nestjs

我正在尝试使用 Nestjs 创建一个简单的测试,但收到此错误

测试函数不能同时接受“完成”回调并返回某些内容。要么使用“完成”回调,要么返回一个承诺。

返回值:Promise{}

单元测试如此简单,但是当我使用done();时出现错误

it('throws an error if a user signs up with an email that is in use', async (done) => {
fakeUsersService.find = () => Promise.resolve([{ id: 1, email: 'a', password: '1' } as User]);
try {
  await service.signup('asdf@asdf.com', 'asdf');
} catch (err) {
  done();
}
});
Run Code Online (Sandbox Code Playgroud)

Ste*_*ott 38

您将 Async/Await 和 Done 结合起来。

要么使用 asnyc/await,要么完成。

it('throws an error if user signs up with email that is in use', async () => {
    try {
        await service();
        expect(...);
    } catch (err) {
    }
});
Run Code Online (Sandbox Code Playgroud)

或使用完成格式

it('throws an error if user signs up with email that is in use', (done) => {
    ...
    service()
     .then( ...) {}
     .catch( ...) {}
    }
    done();
});
Run Code Online (Sandbox Code Playgroud)


Amr*_*man 15

对于 jest 的最后一个版本,你不能同时使用`async/await、promise 和done。

解决方案是

 it("throws an error if user sings up with email that is in use", async () => {
    fakeUsersService.find = () =>
      Promise.resolve([{ id: 1, email: "a", password: "1" } as User]);
    await expect(service.signup("asdf@asdf.com", "asdf")).rejects.toThrow(
      BadRequestException
    );
  });
Run Code Online (Sandbox Code Playgroud)

BadRequestException根据您的听力异常情况进行更改