我正在使用mocha作为测试框架,我正在尝试模拟DELETE
请求,该请求使用fetch针对返回HTTP状态代码{{1 }}
这是测试代码:
204
返回以下输出:
it('should logout user', (done) => {
nock(<domain>)
.log(console.log)
.delete(path)
.reply(204, {
status: 204,
message: 'This is a mocked response',
});
api.logout(token)
.then((response) => {
console.log('IS DONE?--->', nock.isDone());
console.log('RESPONSE--->', response);
done();
})
.catch((error) => {
console.log('ERROR--->', error);
});
});
正如您所看到的那样,matching <domain> to DELETE <domain>/<path>: true
(the above line being generated by the .log method in nock)
IS DONE?---> true
RESPONSE---> {}
和log()
nock方法正确地拦截了请求,但是返回的isDone()
对象是一个空对象,所以不可能对返回的HTTP状态代码进行断言(在本例中为response
)
知道我在这里可能缺少什么?为什么204
方法会返回一个空对象?
更新
以下是reply()
方法的代码,logout
方法是使用remove
HTTP方法的fetch
请求的包装。
DELETE
答案 0 :(得分:1)
我认为204不应该有响应body,因此您可能需要将其更改为200.服务器当然可以返回响应,但我认为fetch不会处理它。像request这样的其他包将处理具有204状态的正文,但此请求包仅用于服务器端。
还不确定你的包装器做了什么,但我认为你需要使用response.json()promise来获取响应。而且mocha也可以自动处理promises,你可以返回它们。请参阅下面的完整示例:
const nock = require('nock')
const fetch = require('isomorphic-fetch');
const request = require('request')
const domain = "http://domain.com";
const path = '/some-path';
const token = 'some-token';
const api = {
logout: (token) => {
return fetch(domain + path, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
}
});
}
}
describe('something', () => {
it('should logout user with 204 response using request package', (done) => {
nock(domain)
.log(console.log)
.delete(path)
.reply(204, {
status: 204,
message: 'This is a mocked response',
});
request.delete(domain + path, function(err, res) {
console.log(res.body);
done(err);
})
});
it('should logout user', () => {
nock(domain)
.log(console.log)
.delete(path)
.reply(200, {
status: 200,
message: 'This is a mocked response',
});
return api.logout(token)
.then((response) => {
console.log('IS DONE?--->', nock.isDone());
return response.json();
})
.then(function(body) {
console.log('BODY', body);
})
.catch((error) => {
console.log('ERROR--->', error);
});
});
});
这将输出:
something
matching http://domain.com:80 to DELETE http://domain.com:80/some-path: true
{"status":204,"message":"This is a mocked response"}
✓ should logout user with 204 response
matching http://domain.com:80 to DELETE http://domain.com:80/some-path: true
IS DONE?---> true
BODY { status: 200, message: 'This is a mocked response' }
✓ should logout user
使用deps:
"dependencies": {
"isomorphic-fetch": "^2.2.1",
"mocha": "^3.2.0",
"nock": "^9.0.6",
"request": "^2.79.0"
}
我希望它有所帮助。