我对sinon和proxyquire还是很陌生,我想我已经在这里阅读了所有的答案,但是我仍然找不到我需要的东西。无论如何,这是我代码的经过消毒的版本。
const fetch = require('node-fetch');
async function deleteID(id, endpoint) {
try {
let url = `${endpoint}/delete/${id}`;
let res = await fetch(url, { method: 'DELETE' });
res = await res.json(); // <---- THIS FAILS WHEN fetch IS MOCKED
// do stuff with res
} catch (err) {
logger.error(`Error: ${JSON.stringify(err)}`);
}
}
非常简单,它使用node-fetch命中URL,然后在请求成功或失败时进行处理。这是我的测试,让我们设置要提取的模型:
const proxyquire = require('proxyquire').noCallThru();
const sinon = require('sinon');
beforeEach((done) => {
const validResponse = {
status: 200,
data: 'hello, world\n'
};
deleteProxy = proxyquire('./delete', {
'node-fetch': sinon.stub().returns(Promise.resolve(JSON.stringify(validResponse)))
});
});
因此,fetch调用现在返回validResponse,而不是访问服务器。这是我的测试:
it.only('should delete', async () => {
try {
deleteProxy.deleteID('id', 'endpoint');
} catch (err) {
expect(err.message).to.have.lengthOf.at.least(0);
}
});
此操作失败,因为res只是具有状态和数据的对象,它不是具有Body等的正确响应...我们的其余代码使用node-mocks-http,但所有测试都使用就像我在上面所做的那样,该模块直接而非通过获取直接访问了URL。
我如何创建模拟的响应以适合上述测试,或者我应该使用其他方法吗?
[通过查看代码和我对sinon的经验,我会说,因为这不是实际的HTTP响应,所以您也必须模拟json()
。在beforeEach
方法中:
const body = {
status: 200,
data: 'hello, world\n'
};
var validResponse = { json: () => { return body } };
deleteProxy = proxyquire('./delete', {
'node-fetch': sinon.stub().returns(Promise.resolve(validResponse))
});
尝试使用JSON.stringify()
让我知道它是否不起作用。