How do you test asynchronous code?
Answer
Testing async code requires test frameworks that support async operations. JavaScript/Jest: return a Promise or use async/await: test("fetches user", async () => { const user = await fetchUser(1); expect(user.name).toBe("Alice"); });. Use done callback for callback-style async. Mock async functions: jest.fn().mockResolvedValue(data). C# (xUnit/NUnit): async Task test methods are natively supported: [Fact] public async Task TestAsync() { var result = await service.GetAsync(); Assert.Equal("expected", result); }. Python (pytest-asyncio): @pytest.mark.asyncio async def test_fetch(): result = await fetch_data(); assert result == expected. Common pitfalls: forgetting to await (test passes even if async code throws); not handling rejection (unhandled promise rejections may not fail tests in some frameworks); real timers causing timeouts. Use fake timers (jest.useFakeTimers()) for time-dependent async code. waitFor utility (React Testing Library) waits for assertions to pass in async UI tests.
Previous
What is the difference between unit tests and integration tests for databases?
Next
What is test containerization with Testcontainers?