【发布时间】:2019-11-14 18:54:26
【问题描述】:
似乎有很多不同的方法可以做到这一点,但我试图只使用 sinon、sinon-test、chai/mocha、axios、httpmock 模块。我无法成功模拟使用 axios 进行的 GET 调用。我希望能够模拟来自该 axios 调用的响应,因此单元测试实际上不必发出外部 API 请求。
我已尝试通过创建沙箱来设置基本单元测试,并使用 sinon 存根设置 GET 调用并指定预期响应。我对 JavaScript 和 NodeJS 不熟悉。
// Main class (filename: info.js)
function GetInfo(req, res) {
axios.get(<url>).then(z => res.send(z.data));
}
// Test class (filename: info.test.js)
it ("should return info", () => {
const expectedResponse = "hello!";
const res = sinon.spy();
const aStub = sinon.stub(axios, "get").resolves(Promise.resolve(expectedResponse));
const req = httpMock.createRequest({method:"get", url:"/GetInfo"});
info.GetInfo(req, res);
// At this point, I need to evaluate the response received (which should be expectedResponse)
assert(res.data, expectedResponse); // data is undefined, res.status is also undefined
// How do I read the response received?
});
我需要知道如何读取应该发回的响应(如果它首先被 sinon 捕获)。
【问题讨论】:
标签: javascript node.js axios sinon sinon-chai