Mocking & SpiesBeginner
1Question 1 of 1
javascriptHow do Mocks and Spies work in Jest (jest.fn, jest.spyOn)?
Explanation & Concept
• `jest.fn()`: Creates a mock function that tracks calls, arguments, and return values. • `jest.spyOn()`: Wraps an existing method on an object to track calls while optionally preserving or overriding its implementation.
Code Example
javascript
import * as userService from "./userService";
test("sends welcome email on registration", async () => {
// Spy on email sending method and mock implementation
const emailSpy = jest.spyOn(userService, "sendEmail").mockResolvedValue(true);
await userService.registerUser({ email: "test@example.com" });
// Assertions
expect(emailSpy).toHaveBeenCalledTimes(1);
expect(emailSpy).toHaveBeenCalledWith("test@example.com", expect.any(String));
emailSpy.mockRestore(); // Restore original implementation
});How It Works & Key Takeaways
Spies allow asserting that side-effect functions (like email senders or analytics trackers) were invoked correctly without sending real emails in unit tests.
Mock Test · 1 Questions · Optional
Ready for Snapshot Testing?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner3 questions