我正在为我的应用编写单元测试,该应用将进行第三方API调用。我正在使用nock模拟API调用。 API使用用户名和密码进行基本身份验证。
这是一个对用户进行身份验证然后返回响应的单元测试。
describe('Authentication tests', () => {
it('Authenticates user', (done) => {
nock('<MY_URL>')
.get('/api/now/table/test_table/test_sys_id')
.basicAuth({user: 'user', pass: 'pass'})
.reply(200, {'a': 'b'});
let snowClient = require('../Client');
snowClient = new snowClient('<MY_URL>', 'user', 'pass', 'application/json', 'application/json');
snowClient.getSingleRecord('test_table', 'test_sys_id', (response) => {
console.log(response);
expect(typeof response).to.be.a('string');
// expect(JSON.parse(response).a).to.equal('b');
done();
});
});
});
但是当我运行此测试时,nock抛出以下错误:
Error: Nock: No match for request {
"method": "GET",
"url": "<MY_URL>/api/now/table/test_table/test_sys_id",
"headers": {
"accept": "application/json",
"content-type": "application/json",
"host": "<MY_URL>"
}
}
但是当我从nock删除.basicAuth()
时,它可以正常工作。我在这里想念什么?这是使用nock测试经过身份验证的API调用的正确方法吗?
编辑:
这是getSingleRecord
的代码:
getSingleRecord(table, sysId, callback){
new Promise((resolve, reject) => {
var requestParams = utils.setRequestParamsWithoutBody(this.headers,
this.auth,
'GET',
utils.URLBuilder(this.instance, this.namespace, this.apiName, table, sysId));
request(requestParams, (err, res) => {
var errorMessage = this._handleErrors(res, err);
if (errorMessage){
return reject(errorMessage);
}
resolve(res.body);
});
}).then((response) => {
callback(response);
}).catch((error) => {
callback(error);
});
}
答案 0 :(得分:0)
我认为您不应该在其中使用nock,应该在这样的描述范围内先于其使用nock,我还没有测试它,我只是研究了它并认为它应该如此工作。
describe('Authentication tests', () => {
let MY_URL = 'you url'
beforeEach(() => {
nock(MY_URL)
.get('/api/now/table/test_table/test_sys_id')
.basicAuth({user: 'user', pass: 'pass'})
.reply(200, {'a': 'b'});
});
it('Authenticates user', (done) => {
let snowClient = require('../Client');
snowClient = new snowClient(MY_URL, 'user', 'pass', 'application/json', 'application/json');
snowClient.getSingleRecord('test_table', 'test_sys_id', (response) => {
console.log(response);
expect(typeof response).to.be.a('string');
// expect(JSON.parse(response).a).to.equal('b');
done();
});
});
});