首页 > 解决方案 > Nock 标头 - 错误:Nock:与请求不匹配

问题描述

这是我的示例代码,由于某种原因,Nock 对我来说失败了,因为在添加标题时它无法匹配 URL,当像下面的测试通过注释代码时。我不明白为什么 nock 不理解标题,因为文档说要这样做,我已经这样做了: reqheaders: { 'authorization' : 'Basic Auth' }

希望有人能找到我正在做的奇怪的事情。

const axios = require('axios');

async function postAPI(params) {
    let response1 = '';
    try {
        response1 =  await axios.post('http://someurl/test2', params);
        
    } catch(error) {
        throw error;
    }

    try {
        console.log("Im here", response1.data.sample)
    const response = await axios.get('http://testurl/testing', {
        // headers: {
        //   'authorization' : 'Basic Auth' //+ response1.data.sample 
        // }
       });
       return response.data;
    
    } catch(err) {
            console.log("Error", err)
    }
}

exports.postAPI = postAPI;

测试

it('make an api call - POST', async () => {

      nock('http://someurl')
      .persist()
      .defaultReplyHeaders({
        'access-control-allow-origin': '*',
        'access-control-allow-credentials': 'true' 
      })
        .post('/test2')
        .reply(200, {
                sample : 'test2'     
  });

    const test = nock('http://testurl', {
    //  reqheaders: {
    //    'authorization' : 'Basic Auth'
    //  }
    })
    .defaultReplyHeaders({
      'access-control-allow-origin': '*',
      'access-control-allow-credentials': 'true'
    })
      .get('/testing')
      .reply(200, { data : 'test' });

      const response = await postAPI();
      console.log("XXXX", response)
      expect(response.data).toEqual("test");
    });

标签: node.jstestingjestjsnock

解决方案


您的 reqheaders 必须与您在 axios 请求标头中传递的内容相匹配。

reqheaders: {
    'authorization' : 'Basic Auth test2'
}

当您在主函数中连接授权标头时,请记住在 Auth 和 response1.data.sample 之间添加一个空格 :)

'authorization' : 'Basic Auth ' + response1.data.sample

我试过你的代码,它可以工作。全面测试:

const nock = require('nock');
const { postAPI } = require('./index');
const { expect } = require('chai');

describe('postapi', () => {
    it('make an api call - POST', async () => {

        nock('http://someurl')
        .defaultReplyHeaders({
          'access-control-allow-origin': '*',
          'access-control-allow-credentials': 'true' 
        })
          .post('/test2')
          .reply(200, {
                  sample : 'test2'     
        });
    
        nock('http://testurl', {
            reqheaders: {
            'authorization' : 'Basic Auth test2'
            }
        })
        .defaultReplyHeaders({
            'access-control-allow-origin': '*',
            'access-control-allow-credentials': 'true'
        })
        .get('/testing')
        .reply(200, { data : 'test' });
    
        const response = await postAPI();
        console.log("XXXX", response)
        expect(response.data).to.be.eql("test");
      });
});

推荐阅读