DEV Community

Discussion on: Stubs vs Mocks in JS

Collapse
 
snikhill profile image
Nikkhiel Seath

Thank you for explaining the difference in simple terms.

So, I should use:
A stub if all I care about is the final change in state/value.
and a mock if I care about both the final change in state/value along with how that change was brought.
E.g.: a function that returns a certain value and has a timeout / retry functionality until a certain condition is met and if:

  • I care about just the returned value: I shall use a stub
  • I care about the returned value + the no. of retries: I shall use a mock

Like, I shall use a mock if I have a function that generates unique ids and part of its process is to re-generate a new id if the currently generated id already exists.
And in this case, I shall like to test:
a) That I get a unique id
b) If my dataset already contains the generated id then, I need to confirm that the generation process is called more than once until a unqiue id is found.

Collapse
 
cerchie profile image
Lucia Cerchie

Wow such a thoughtful response! Another great example of the difference.