Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different response with same scope & path with different auth header with Nock, possible?

I'm using 3rd party API which has /places endpoint which returns the information of the places the authenticated user has permissions as JSON. That API is using JWT as authentication, the token is placed in X-Auth-Token header.

My project has a service which authenticates to that 3rd party API with multiple user accounts. One of my test cases is testing that service so that the /places gets called two times. The service authenticates to the 3rd party API and sets the token to X-Auth-Token before requesting /places.

I've tried to make a mock of the 3rd party API as follows:

nock(apiUrl)
  .matchHeaders("x-auth-token", firstToken)
  .get(/places/)
  .reply(200, placeList1);
nock(apiUrl)
  .matchHeaders("x-auth-token", secondToken)
  .get(/places/)
  .reply(200, placeList2)

But Nock throws me error that there was no match for the request. If I try

nock(apiUrl)
  .matchHeaders("x-auth-token", (value) => {
    console.log(value)
    return value === firstToken;
  })
  .get(/places/)
  .reply(200, placeList1);

I can see that the value of the X-Auth-Token is correct for one of the requests but the endpoint won't still match.

Am I doing something wrong? Or is it even possible to have multiple requests to same path of the same scope with different responses with Nock? As my service is using Promises I can't rely on the order in which the requests are created.

I'm using request-promise-native in my service and running my tests with Mocka.

like image 496
Masza Avatar asked Jan 31 '26 16:01

Masza


1 Answers

For someone who stumbles on this question, you can certainly have different responses from the same path using nock chaining.

You can try something like:

nock(apiUrl)
.matchHeader("x-auth-token", firstToken)
.get(/places/)
.reply(200, placeList1)
.matchHeader("x-auth-token", secondToken)
.get(/places/)
.reply(200, placeList2)
like image 59
Sarneet Kaur Avatar answered Feb 02 '26 19:02

Sarneet Kaur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!