Problem:
I want to mock a situation in which on the same http call I get different results. Specifically, the first time it fails.
To some extent this is similar to Sinon capability of stub.onFirstCall()
, stub.onSecondCall()
Expectation:
I expected that if I use once
on the first call and twice
on the second call I would be able to accomplish the above.
nock( some_url )
.post( '/aaaa', bodyFn )
.once()
.reply( 500, resp );
nock( some_url )
.post( '/aaaa', bodyFn )
.twice()
.reply( 200, resp );
HTTP server mocking and expectations library for Node.js. Nock can be used to test modules that perform HTTP requests in isolation. For instance, if a module performs HTTP requests to a CouchDB server or makes HTTP requests to the Amazon API, you can test that module in isolation.
Just like in the architectural diagram, Nock sits in between the backend application and the frontend application and intercepts any request being tested. Instead of calling the backend service to test the application, you provide a set of known responses that simulate (mock) the application.
The correct way is to simply
call Nock
twice.
nock( some_url )
.post( '/aaaa', bodyFn )
.reply( 500, resp );
nock( some_url )
.post( '/aaaa', bodyFn )
.reply( 200, resp );
The way Nock works is that each call registers an interceptor for some_url
.
In fact the first time you call some_url
will clear the first interceptor and so on.
as stated in docs:
When you setup an interceptor for a 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. It also means that you must setup one interceptor for each request you are going to have, otherwise nock will throw an error because that URL was not present in the interceptor list. If you don’t want interceptors to be removed as they are used, you can use the .persist() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With