nock not setting the authorization header in react

392 views Asked by At

Trying to mock the headers of authorization bearer token and few other headers in nock but nock is erroring out Nock: No match for request.

It works without the headers and reqheaders though...

Axios call

const details = await axios
    .get(serviceUrl, {
        params,
        headers: {
            authorization: `Bearer <token>`
        }
    })
    .then(response => {
        if (response.statusText !== 'OK') {
            throw new Error('Error');
        }
        return response.data;
    })
    .catch(error => {
        return error;
    });

Nock mocking

nock(baseUrl, {
        reqheaders: {
            authorization: `Bearer <token>`
        }
    })
        .defaultReplyHeaders({
            'access-control-allow-origin': '*',
            'access-control-allow-credentials': 'true'
        })
        .get('/v1/service')
        .query(query)
        .reply(200, details)
2

There are 2 answers

0
Explorer On BEST ANSWER

I had to intercept the pre-flight (cores) request with the response headers to make this work.

Reference: https://github.com/nock/nock/issues/1534

nock(baseUrl)
.persist()
.intercept(
    `${baseUrl}?q1=query1&q2=query2`,
    'OPTIONS'
)
.reply(200)
.defaultReplyHeaders({
    'access-control-allow-origin': '*',
    'access-control-allow-headers': ['Authorization', 'x-otherHeaders']
})
.get('/v1')
.query({ q1: 'query1', q2: 'query2' })
.reply(200, data);
0
Lin Du On

It works fine for me.

index.test.ts:

import axios from 'axios';
import nock from 'nock';

axios.defaults.adapter = require('axios/lib/adapters/http')

describe('74738889', () => {
  test('should pass', async () => {
    const query = { id: 1 };
    const details = { id: 1, name: 'teresa teng' };
    const scope = nock('http://localhost', {
      reqheaders: {
        authorization: `Bearer <token>`
      }
    })
      .defaultReplyHeaders({
        'access-control-allow-origin': '*',
        'access-control-allow-credentials': 'true'
      })
      .get('/v1/service')
      .query(query)
      .reply(200, details)


    const res = await axios.get('http://localhost/v1/service', {
      params: query,
      headers: {
        authorization: `Bearer <token>`
      }
    });
    console.log('res.data: ', res.data);
    console.log('res.headers', res.headers)
    expect(res.data).toEqual(details);

    scope.done()
  })
})

Test result:

 PASS  stackoverflow/74738889/index.test.ts (10.169 s)
  74738889
    ✓ should pass (30 ms)

  console.log
    res.data:  { id: 1, name: 'teresa teng' }

      at stackoverflow/74738889/index.test.ts:30:13

  console.log
    res.headers {
      'content-type': 'application/json',
      'access-control-allow-origin': '*',
      'access-control-allow-credentials': 'true'
    }

      at stackoverflow/74738889/index.test.ts:31:13

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.668 s, estimated 11 s

package versions:

"nock": "^13.2.9",
"axios": "^0.21.1",