【问题标题】:How to call a fakeServer in Sinon.JS / Node如何在 Sinon.JS / Node 中调用 fakeServer
【发布时间】:2014-11-06 22:51:07
【问题描述】:

我正在努力弄清楚如何在我的单元测试中使用 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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

      • 这很简单,因为 Node 没有 XMLHttpRequest 对象 :) 你需要为 sinon 添加一个像 node-XMLHttpRequest 这样的假对象。
      猜你喜欢
      • 2012-03-10
      • 2015-04-02
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      相关资源
      最近更新 更多