Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do subsequent calls on same url via Nock having different status code

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 );
like image 931
Dudi Avatar asked Mar 04 '19 18:03

Dudi


People also ask

What is a characteristic of the Nock library?

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.

How do Nocks work?

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.


1 Answers

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.

like image 117
Dudi Avatar answered Oct 06 '22 06:10

Dudi