reactjs nock未在react中设置授权头

cclgggtu  于 2022-12-12  发布在  React
关注(0)|答案(1)|浏览(103)

尝试在nock中模拟授权承载令牌的标头和其他一些标头,但nock错误输出Nock: No match for request
它的工作没有头和reqheader虽然...
Axios呼叫

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

vi4fp9gy1#

对我来说很好。
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()
  })
})

检测结果:

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

软件包版本:

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

相关问题