我正在努力弄清楚如何在我的单元测试中使用 sinon 来伪造服务器。
他们文档中的例子是:
setUp: function () {
this.server = sinon.fakeServer.create();
},
"test should fetch comments from server" : function () {
this.server.respondWith("GET", "/some/article/comments.json",
[200, { "Content-Type": "application/json" },
'[{ "id": 12, "comment": "Hey there" }]']);
var callback = sinon.spy();
myLib.getCommentsFor("/some/article", callback);
this.server.respond();
sinon.assert.calledWith(callback, [{ id: 12, comment: "Hey there" }]));
}
不幸的是,我不知道 myLib.getCommentsFor(...)
中发生了什么,所以我不知道如何实际访问服务器。
所以在 Node 中,我正在尝试以下...
sinon = require('sinon');
srv = sinon.fakeServer.create();
srv.respondWith('GET', '/some/path', [200, {}, "OK"]);
http.get('/some/path') // Error: connect ECONNREFUSED :(
很明显,http 还是认为我要的是真服务器,那怎么连接到假服务器呢?
最佳答案
Sinon 正在覆盖浏览器的 XMLHttpRequest 以创建 FakeXMLHttpRequest。您需要找到一个 Node XHR 包装器,例如 https://github.com/driverdan/node-XMLHttpRequest让 Sinon 拦截来自代码的调用。
关于node.js - 如何在 Sinon.JS/Node 中调用 fakeServer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26790942/