我正在尝试使用Lab和 Sinon 为我的文件中调用的各种 HTTP 请求编写一些测试。我遵循了http://sinonjs.org/上的 Fake XMLHttpRequest 示例,但是当我运行我的测试时,它似乎实际上并没有捕获任何请求。
这是(相关的)测试代码:
context('when provided a valid payload', function () {
let xhr;
let requests;
before(function (done) {
xhr = sinon.useFakeXMLHttpRequest();
requests = [];
xhr.onCreate = function (req) { requests.push(req); };
done();
});
after(function (done) {
// clean up globals
xhr.restore();
done();
});
it('responds with the ticket id', (done) => {
create(internals.validOptions, sinon.spy());
console.log(requests); // Logs empty array []
done();
});
});
create 是我从另一个文件中导入的函数,这里:
internals.create = async function (request, reply) {
const engineeringTicket = request.payload.type === 'engineering';
const urgentTicket = request.payload.urgency === 'urgent';
if (validation.isValid(request.payload)) {
const attachmentPaths = formatUploads(request.payload.attachments);
const ticketData = await getTicket(request.payload, attachmentPaths);
if (engineeringTicket) {
const issueData = getIssue(request.payload);
const response = await jira.createIssue(issueData);
jira.addAttachment(response.id, attachmentPaths);
if (urgentTicket) {
const message = slack.getMessage(response);
slack.postToSlack(message);
}
}
zendesk.submitTicket(ticketData, function (error, statusCode, result) {
if (!error) {
reply(result).code(statusCode);
} else {
console.log(error);
}
});
} else {
reply({ errors: validation.errors }).code(400); // wrap in Boom
}
};
如您所见,它调用 jira.createIssue 和 zendesk.submitTicket,两者都使用 HTTP 请求将一些有效负载发布到 API。但是,运行测试后,requests 变量仍然为空,似乎没有捕获任何请求。由于没有创建票证/问题,因此绝对没有实际提交请求,我需要修复什么才能实际捕获请求?