Sinon FakeServer没有请求?

时间:2016-06-17 01:18:32

标签: jquery unit-testing reactjs mocha sinon

我正在关注SinonJS Fake Server tutorial并且我正在运行这个简单的代码:

var server;

before(function () { server = sinon.fakeServer.create(); });
after(function () { server.restore(); });

it("calls callback with deserialized data", function () {
    var callback = sinon.spy();
    getTodos(42, callback);

    // This is part of the FakeXMLHttpRequest API
    server.requests[0].respond(
        200,
        { "Content-Type": "application/json" },
        JSON.stringify([{ id: 1, text: "Provide examples", done: true }])
    );

    assert(callback.calledOnce);
});

我在同一个文件中包含了getTodos函数。这也是:

function getTodos(listId, callback) {
    $.ajax({
         url: "/todo/" + listId + "/items",
         success: function (data) {
             // Node-style CPS: callback(err, data)
             callback(null, data);
         }
    });
}

但是,我收到错误TypeError: Cannot read property 'respond' of undefined。看起来server.requests是空的 - 这是为什么?如何确保请求出现?

更新:我能够缩小范围。我添加了一个"错误"回调getTodos函数,并为错误执行console.log。事实证明,来自jsdom节点模块的语法错误试图执行urlObj = new URL(uri, documentBaseURLSerialized(this._ownerDocument));,然后导致$.ajax({失败。任何人对此都有任何想法?

2 个答案:

答案 0 :(得分:2)

我能想到的一个问题是你没有在你的JSDom实例中加载Sinon。这是一个可在此处运行的测试文件:

var jsdom = require("jsdom");
var assert = require("assert");

var vc = jsdom.createVirtualConsole();
vc.on("log", console.log.bind(console.log));
vc.on("jsdomError", function jsdomError(er) {
    throw er;
});

var window;
var $;
var sinon;
before(function (done) {
    jsdom.env({
        html: "",
        scripts: ["node_modules/jquery/dist/jquery.js",
                  "node_modules/sinon/pkg/sinon.js"],
        features: {
            ProcessExternalResources: ["script"],
            FetchExternalResources: ["script", "link"],
        },
        virtualConsole: vc,
        done: function _done(error, w) {
            if (error) {
                throw error;
            }
            window = w;
            $ = w.$;
            sinon = w.sinon;
            done();
        },

    });
});


function getTodos(listId, callback) {
    $.ajax({
         url: "/todo/" + listId + "/items",
         success: function (data) {
             // Node-style CPS: callback(err, data)
             callback(null, data);
         }
    });
}

var server;

before(function () { server = sinon.fakeServer.create(); });
after(function () { server.restore(); });

it("calls callback with deserialized data", function () {
    var callback = sinon.spy();
    getTodos(42, callback);

    // This is part of the FakeXMLHttpRequest API
    server.requests[0].respond(
        200,
        { "Content-Type": "application/json" },
        JSON.stringify([{ id: 1, text: "Provide examples", done: true }])
    );

    assert(callback.calledOnce);
});

答案 1 :(得分:0)

只需使用:

var { JSDOM } = require('jsdom')
var dom = new JSDOM
window = dom.window
window.XMLHttpRequest = sinon.useFakeXMLHttpRequest()