Labs ICT
Pro Login

Stubs vs Mocks

Understanding the difference.

Stubs vs Mocks

People use stubs and mocks interchangeably, and honestly, the difference does not always matter in practice. But understanding the distinction will make you a better tester and help you communicate with your team.

Let me give you the simple breakdown that finally made sense to me.

What Is a Stub?

A stub is a fake that replaces a dependency and returns a predetermined value. It does not care about how it was called. It just gives you a fixed response.


const stub = jest.fn().mockReturnValue({ name: 'Alice', age: 25 });

it('uses stub data', () => {
  const user = stub(1);
  expect(user.name).toBe('Alice');
});
    

Notice we never checked how many times the stub was called or what arguments it received. A stub just sits there and gives you data.

What Is a Mock?

A mock goes further. It not only replaces the dependency but also tracks how it was called. You can assert that it was called a certain number of times, with specific arguments, in a specific order.


const mock = jest.fn().mockReturnValue('done');

it('verifies mock was called correctly', () => {
  mock('hello');
  mock('world');

  expect(mock).toHaveBeenCalledTimes(2);
  expect(mock).toHaveBeenNthCalledWith(1, 'hello');
  expect(mock).toHaveBeenNthCalledWith(2, 'world');
});
    

When to Use Which?

Use a stub when you just need to provide test data and do not care about the interaction. Use a mock when you need to verify that your code interacted with the dependency correctly.

In Jest, the line is blurry because jest.fn() does both. But thinking about whether you need to verify calls or just provide data will guide your testing decisions.

The Practical Difference

Think of it like this. A stub is like a vending machine that gives you a soda. A mock is like a vending machine that gives you a soda and logs that you bought one. Both give you the soda, but the mock also watches your behavior.

Try it Yourself →

Key Takeaways

  • Stubs provide predetermined responses without tracking calls
  • Mocks provide responses and verify how the dependency was used
  • In Jest, jest.fn() can act as either a stub or a mock
  • Use stubs when you just need test data
  • Use mocks when you need to verify interactions