Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a fakeServer in Sinon.JS / Node

I'm struggling to figure out how to use sinon to fake a server in my unit tests.

The example in their documentation is:

    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" }]));
    }

Unfortunately, I don't know what's going on in myLib.getCommentsFor(...), so I can't tell how to actually hit the server.

So in node, I'm trying the following...

sinon = require('sinon');

srv = sinon.fakeServer.create();

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

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

Obviously, http still thinks I want a real server, so how do I connect to the fake one?

like image 988
Thomas Avatar asked Nov 09 '22 23:11

Thomas


1 Answers

Sinon is overriding the browser's XMLHttpRequest to create FakeXMLHttpRequest. You'll need to find a node XHR wrapper such as https://github.com/driverdan/node-XMLHttpRequest to have Sinon intercept the calls from the code.

like image 150
Gabriel Kohen Avatar answered Nov 14 '22 22:11

Gabriel Kohen