Sinon FakeServer no requests?

假装没事ソ 提交于 2019-12-01 14:01:59

The one issue I can think of is that you did not load Sinon in your JSDom instance. Here is a test file that works here:

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

Just use:

var { JSDOM } = require('jsdom')
var dom = new JSDOM
window = dom.window
window.XMLHttpRequest = sinon.useFakeXMLHttpRequest()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!