Search code examples
reactjshttpaxiosmockingnock

nock not setting the authorization header in react


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)

Solution

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