Mocking api calls with nock…
I’ve been playing around w/ nock for a while now and I really enjoy using it. I’m using it to mock my api calls to youtube for testing and it’s worked out great.
Some things to note…
- When using it with an api that accepts a list of things, like ids, sort the ids first — else the endpoint might not match the request because the ids aren’t in a given order.
- If you want to hit an endpoint more than once, one must either set up multiple nocks or use .persist() because:
When you setup an interceptor for an URL and that interceptor is used, it is removed from the interceptor list. This means that you can intercept 2 or more calls to the same URL and return different things on each of them.
Here is a simple example of mocking a youtube api request using mocha, nock, request-promise, and chai…