I'm writing some jest tests to test an async method. If I run each test individually, it works! However, when I run the whole suite, they fail. The mock values from one test end up in another test because I suspect that jest is not waiting for one to finish before moving onto another.
describe('testing method', () => {
test('test case 1', async () => {
dependentService.method.mockResolvedValueOnce(mockResult1);
expect(await testSubject(input)).toBe(expectedResult);
});
test('test case 2', async () => {
dependentService.method.mockResolvedValueOnce(mockResult2);
expect(await testSubject(input)).toBe(expectedResult);
});
});
In the above sample code snippet, the mockResult2 is used in the test case 1, instead of mockResult1. How do I get this to behave as I expect?
CodePudding user response:
Changing up the expect
syntax will solve the problem.
await expect(testSubject(input)).resolves.toBe(expectedResult)
The toBe
part of that line is mandatory - without it jest wont wait for the promise to resolve and the framework will mix up promises across tests.
CodePudding user response:
Jest executes all testcases in parallel but you can execute serially by adding this flag
jest --runInBand