dwyl / book

📗 Our Book on Full-Stack Web Application Development covering User Experience (UX) Design, Mobile/Offline/Security First, Progressive Enhancement, Continuous Integration/Deployment, Testing (UX/TDD/BDD), Performance-Driven-Development and much more!
https://dwyl.github.io/book/
820 stars 134 forks source link

Mocking? Why When & How to Mock in your Tests #54

Open nelsonic opened 8 years ago

nelsonic commented 8 years ago

Why?

_Situation_: You want to use a service (API) made by someone else in your project, but you don't want to call that API inside your tests because the network is slow/unreliable or simply because the service requires multi-step (user-input) authentication (e.g: OAuth2) and you don't want to go through that in your tests.

What?

In unit testing a _Mock_ is used to simulate an object or response (from an API) in a controlled way.

How?

Lets say you are building an app called "_BroLee?_" that gives people recommendations on when they should carry an umbrella to wear based on the weather conditions in their location.

Example:

_nock_ is made by @pgte and is the _gold standard_ in simplified libraries.

Notes

nelsonic commented 8 years ago

Mocking is the equivalent of doing:

var sky = 'blue'
assert.equal(sky, 'blue');

Always true. tests nothing.

nelsonic commented 8 years ago

https://www.sitepoint.com/sinon-tutorial-javascript-testing-mocks-spies-stubs/