node.js - 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");
});
解决方案
您的 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");
});
});
推荐阅读
- c++ - 我收到此代码的分段错误?
- typescript - Typescript、Babel 7、Karma、Jasmine、代码覆盖率配置
- ios - 选中时 Tabman 图像色调颜色
- python - 使用python为每行的唯一代码创建新列
- algorithm - 在 goroutine 中设置广播和多接收
- ajax - 如何使用ajax从数据库中获取最后一条记录
- python - Django在用户模型中显示多对多关系
- c++ - 用数据填充 QVector 的最有效方法是什么?
- vue.js - Facebook Oauth2 无法手动打开同意对话框 Vuejs
- android - 如何在 Android 中创建水平和垂直滚动的列表视图?