这是我的示例代码,由于某种原因,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");
});发布于 2020-11-20 05:07:44
您的reqheader必须与您在axios中传递的requst头匹配。
reqheaders: {
'authorization' : 'Basic Auth test2'
}在main函数中连接authorization头时,请记住在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");
});
});https://stackoverflow.com/questions/64451314
复制相似问题