DEV Community

Discussion on: Stubs vs Mocks in JS

Collapse
 
peerreynders profile image
peerreynders

One thing that may be worth considering: Practices inform tools but tools rarely inform practices.

To some degree your interpretation is guided by Sinon's implementation of a test double tool which ultimately reflects the vision of the Sinon.JS developers.

Martin Fowler references Gerard Mezaros's test double categorization:

  • Dummy Object
  • Test Stub/Spy
  • Mock Object
  • Fake Object

In particular (xUnit Test Patterns, p. 133):

  • A Test Stub is an object that replaces the real component on which the SUT (System Under Test) depends so that the test can control the indirect inputs of the SUT. It allows the test to force the SUT down paths that it might not otherwise exercise. A Test Spy, which is a more capable version of a Test Stub, can be used to verify the indirect outputs of the SUT by giving the test a way to inspect them after exercising the SUT
  • A Mock Object is an object that replaces a real component on which the SUT depends so the that test can verify its indirect outputs.

So

  • A Stub is focused entirely on the value that is returned (i.e. indirect input to the SUT).
  • A Spy also captures the passed inputs like argument values with each invocation ( i.e. indirect outputs from the SUT).
  • A Mock goes even further as expectations can be configured directly on the test double itself — the test can then simply execute a verify command on the Mock to ensure that all expectations have been met at that point in time.

To some degree Fowler's article juxtaposes the Classical (Detroit, Chicago) vs. Mockist (London) schools of TDD (in 2007) and alludes to the fact that mockist tests can have the tendency to couple tests to implementations rather than behaviour (contract, protocol) which can lead to fragile tests.

In 2021 Ian Cooper actually goes as far as saying that mocks should only be used to solve problems of shared fixtures and slow tests rather than isolating dependencies.

Collapse
 
cerchie profile image
Lucia Cerchie

This reply is a blog post in itself! I learned so much about spies! Thank you!