Tho*_*mas 5 unit-testing node.js sinon
我正在努力在单元测试中弄清楚如何使用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" }]));
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不知道发生了什么事myLib.getCommentsFor(...),所以我不知道如何实际打服务器。
所以在节点中,我正在尝试以下操作...
sinon = require('sinon');
srv = sinon.fakeServer.create();
srv.respondWith('GET', '/some/path', [200, {}, "OK"]);
http.get('/some/path') // Error: connect ECONNREFUSED :(
Run Code Online (Sandbox Code Playgroud)
显然,http仍然认为我想要一台真正的服务器,那么如何连接到假服务器呢?
Sinon 正在重写浏览器的 XMLHttpRequest 来创建 FakeXMLHttpRequest。您需要找到一个节点 XHR 包装器(例如https://github.com/driverdan/node-XMLHttpRequest)才能让 Sinon 拦截来自代码的调用。