Tillitsdone
down Scroll to discover

Advanced Mocking with Jest: Test Like a Pro

Master Jest's powerful mocking capabilities with practical examples.

Learn how to effectively use spies, stubs, and mocks to create robust tests for your JavaScript applications.
thumbnail

Advanced Mocking Techniques with Jest: Spies, Stubs, and Mocks

Abstract flowing waves representing testing patterns using light blue and cobalt colors with dynamic interweaving patterns shot from top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Testing modern applications can be tricky, especially when dealing with complex dependencies and external services. That’s where Jest’s advanced mocking capabilities come in handy. Let’s dive deep into the world of spies, stubs, and mocks to level up your testing game.

Understanding the Basics

Before we jump into the advanced stuff, let’s quickly refresh our understanding of these testing tools:

  • Spies: Think of them as watchful observers that track how functions are used
  • Stubs: Like stand-ins for real functions, providing predetermined responses
  • Mocks: The complete replacements that can verify behavior

Spying on Functions

Spies are incredibly useful when you want to ensure that functions are called correctly without changing their actual behavior. Let’s look at a real-world example:

const userService = {
notifyUser: (message) => {
// Complex notification logic
}
};
describe('Notification System', () => {
it('should notify user when important action occurs', () => {
const notifySpy = jest.spyOn(userService, 'notifyUser');
// Trigger some action
performImportantAction();
expect(notifySpy).toHaveBeenCalledWith('Action completed successfully');
});
});

Geometric crystal formations in whisper white and etched glass colors arranged in a spiral pattern captured from a 45-degree angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Mastering Stubs

Sometimes you want to control the behavior of your dependencies completely. That’s where stubs shine:

const fetchUserData = jest.fn().mockImplementation(() => {
return Promise.resolve({
id: 1,
name: 'Test User',
role: 'admin'
});
});
describe('User Management', () => {
it('should handle user data correctly', async () => {
const user = await fetchUserData();
expect(user.role).toBe('admin');
});
});

Creating Sophisticated Mocks

For complex scenarios, you might need to create comprehensive mocks that simulate entire modules or classes:

jest.mock('./databaseService', () => {
return {
connect: jest.fn(),
query: jest.fn().mockImplementation((queryString) => {
if (queryString.includes('SELECT')) {
return Promise.resolve([{ id: 1, data: 'test' }]);
}
return Promise.resolve({ affected: 1 });
}),
disconnect: jest.fn()
};
});

Organic flowing textures in dark green and neon green resembling abstract landscape patterns photographed from a low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Best Practices and Common Pitfalls

  1. Always remember to clear mocks between tests using jest.clearAllMocks()
  2. Use jest.spyOn() when you want to restore original behavior later
  3. Be careful with mock implementations that might cause memory leaks
  4. Consider using jest.isolateModules() for tests that need completely isolated module states

Advanced Techniques

Here’s a powerful technique for testing error conditions:

const mockFn = jest.fn()
.mockImplementationOnce(() => Promise.resolve('success'))
.mockImplementationOnce(() => Promise.reject(new Error('fail')));
describe('Error Handling', () => {
it('should handle success and failure scenarios', async () => {
expect(await mockFn()).toBe('success'); // First call
await expect(mockFn()).rejects.toThrow('fail'); // Second call
});
});

Conclusion

Mastering these advanced mocking techniques will make your tests more robust and maintainable. Remember, the goal is to create tests that are both thorough and readable.

Smooth wave-like formations in navy blue color with hints of breezeway blue creating a fluid dynamic pattern shot from an aerial perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

icons/code-outline.svg Jest Blogs
Versatile testing framework for JavaScript applications supporting various test types.
icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.