node.js - 如何在 Sinon.JS/Node 中调用 fakeServer

标签 node.js unit-testing 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" }]));
    }

不幸的是,我不知道 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/

相关文章:

javascript - stub 和代理

javascript - 如何在node.js中使用Sinon/Mocha模拟变量

Javascript,如何等待多个 promise

javascript - 由于 http.get Angular foreach 而出现 map 标记重复

ruby-on-rails - rails 测试 : Array to be loaded in fixtures

javascript - Jest.fn() 在 React 单元测试中不起作用

node.js - Node Express 测试模拟 res.status(status).json(obj)

javascript - 使用 Exiftool 和 NodeJS 从 JPG 读取标签

javascript - NodeJS + Socket IO 发送过多数据

c++ - 多学生编程解决方案的有效测试