如何在Sinon.JS /节点中调用假服务器

问题描述 投票:5回答:2

我正在努力在单元测试中弄清楚如何使用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(...)中发生了什么,所以我不能说出如何真正打中服务器。

所以在节点中,我正在尝试以下操作...

sinon = require('sinon');

srv = sinon.fakeServer.create();

srv.respondWith('GET', '/some/path', [200, {}, "OK"]);

http.get('/some/path') // Error: connect ECONNREFUSED :(

显然,http仍然认为我想要一台真正的服务器,所以我该如何连接到假服务器?

node.js unit-testing sinon
2个回答
0
投票

Sinon正在重写浏览器的XMLHttpRequest以创建FakeXMLHttpRequest。您需要找到一个节点XHR包装器,例如https://github.com/driverdan/node-XMLHttpRequest,以使Sinon截取来自代码的调用。


0
投票

由于某种原因,当在节点下运行时,sinon不会自动接管XMLHttpRequest。

尝试像这样重写您的setUp函数:

setUp: function () {
    this.server = sinon.fakeServer.create();
    global.XMLHttpRequest = this.server.xhr;
},

您不需要任何其他XMLHttpRequest库。

© www.soinside.com 2019 - 2024. All rights reserved.