如何在Sinon.JS / Node中调用一个fakeServer

5
我正在努力学习如何在单元测试中使用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仍认为我需要一个真实的服务器,那么我怎么连接到假服务器呢?
2个回答

1

0

由于某些原因,当在 Node 环境下运行时,sinon 并不会自动接管 XMLHttpRequest。

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

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

你不应该需要任何其他的XMLHttpRequest库。


这很简单,因为Node没有XMLHttpRequest对象 :) 您需要添加一个假的对象,例如node-XMLHttpRequest,以便使用sinon。 - oligofren

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接