'Test functions cannot both take a 'done' callback

I'm trying to create a simple test with nestjs, and I'm get this error

Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise.

Returned value: Promise {}

The unit test is so simple, but I get an error when I use done();

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


Solution 1:[1]

You are combining Async/Await and Done.

Either use asnyc/await, or done.

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

or use the done format

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

Solution 2:[2]

for the last version from jest, you can't use `async/await , promise and done together.

the solution is

 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("[email protected]", "asdf")).rejects.toThrow(
      BadRequestException
    );
  });

change BadRequestException according to your listening exception

Solution 3:[3]

Before v27, jest use jest-jasmine2 by default.

For version 27, jest uses jest-circus which doesn’t support done callback.

So you need to change the default testRunner.

Override with react-app-rewired worked for me

// config-overrides.js
module.exports.jest = (config) => {
    config.testRunner = 'jest-jasmine2';
    return config;
};

Solution 4:[4]

Also, if you want to use both you can downgrade your current version of jest to : 26.6.3. Worked fine for me, I'm using async + done

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Steven Scott
Solution 2 Amr Abdalrahman
Solution 3 Phúc Tài Lâm
Solution 4 stark max