Performance: Testing async code
This affects test execution speed and responsiveness of test suites, impacting developer feedback loops.
test('fetch data', async () => { const data = await fetchData(); expect(data).toBeDefined(); });
test('fetch data', (done) => {
fetchData().then(data => {
expect(data).toBeDefined();
done();
});
});| Pattern | Test Runner Blocking | Flaky Tests | Execution Time | Verdict |
|---|---|---|---|---|
| Callback without wait | Blocks until timeout | High chance | Longer due to retries | [X] Bad |
| Async/await or returned promise | Non-blocking | Minimal | Faster and reliable | [OK] Good |
async and await in Node.js tests?test('fetch data returns correct value', async () => {
const data = await fetchData();
expect(data).toBe('hello');
});fetchData() returns a promise resolving to 'hello'?test('async error test', async () => {
try {
await asyncFunc();
} catch (e) {
expect(e.message).toBe('fail');
}
});getUser(id) that returns user data or throws if user not found. Which test correctly checks both success and error cases?Pass the test and this pattern moves unknown