Jest is a powerful JavaScript testing framework that simplifies unit testing, integration testing, and beyond. Here are its core features:
1. Mock Functions 🧠
Jest allows you to create mock functions to simulate behavior.
jest.fn().mockReturnValue("mocked");
Use jest.spyOn()
for spying on existing functions.
2. Snapshot Testing 📸
Compare UI outputs against predefined snapshots.
expect(component).toMatchSnapshot();
Snapshots are auto-generated and stored in __snapshots__
folder.
3. Asynchronous Code Support ⏱️
Test async functions with async/await
or done
callbacks.
test("async test", async () => {
await expect(fetchData()).resolves.toBe("success");
});
Use findBy
or wait
for React components.
4. Test Coverage 📊
Analyze code coverage with built-in reporter:
npm test -- --coverage
View results in coverage/
directory.
5. Assertions & Matchers ✅
Rich assertion library:
toBe()
for strict equalitytoContain()
for array inclusiontoThrow()
for error checkingtoHaveLength()
for string/array length
Next Steps 🚀
Explore how to set up Jest in your project or dive into advanced configurations.