Search code examples
node.jssinonnock

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 );

Solution

  • 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.