22

I am trying to run some tests that require stubbing jQuery.ajax. I'm using SinonJS to do that and it used to work fine with older version of jQuery (1.x)

var $ = require('jquery');
var sinon = require("sinon");
sinon.stub($, "ajax"); // this worked because $.ajax is defined

However, after upgrading to jQuery 2.x, I have had to include a window environment when I require jquery from my module for it to run. I am using jsdom to accomplish this:

var document = require('jsdom').jsdom(),
    window  = document.parentWindow,
    $       = require('jquery')(window);

PROBLEM $.ajax is now undefined. I suspect because now it returns the jQuery object bound to a specific element but not entirely sure. Does anyone know why and how to get around this?

EDIT A buddy of mine who isn't on SO has pointed out that if we attach window to global, we can get the plain jquery object instead of the factory

    global.window = require('jsdom').jsdom().parentWindow;
    var $ = require('jquery'); // this works as $.ajax is now defined

I'm not a fan of attaching window to global as it will affect up some of the plugins which type check window. Not a blocker, but I'd love to see if there is any other way to go around this problem.

6
  • JSDom works with io.js and not "deprecated" environments (like node) so maybe an update of your backend will solve it. Commented Apr 29, 2015 at 13:23
  • @BenjaminGruenbaum I'd love to be I have to stick with node for now. I pin jsdom to 3.x so that shouldn't have been a problem. Commented Apr 29, 2015 at 13:24
  • Did you see stackoverflow.com/a/8916217/1348195 ? Commented Apr 29, 2015 at 13:25
  • @BenjaminGruenbaum I did. The question has $.ajax defined. It's just not working. I don't have this function bound to my jQuery object. Commented Apr 29, 2015 at 13:27
  • Why did you want to use jquery ajax ? Request is easier. Commented May 7, 2015 at 15:27

3 Answers 3

7

I could have sworn that after reading jquery source, I tried this on the day I asked the question but it didn't work. I tried again just now and it's working.

tl;dr jQuery attaches $ to the window namespace for browser emulator.

var document    = require('jsdom').jsdom(),
    window      = document.parentWindow;
require('jquery')(window);
var $ = window.$;

Hopefully it's useful to someone else.

Sign up to request clarification or add additional context in comments.

Comments

7
+100

While Stubs are nice, they are not as good as Fakes which are not as good as Mocks. I would advise using the more intriguing features of Sinon to create Fakes.

Rather than stubbing the window.$, you can fake the XMLHttpRequest and or XMLHttpResponse

var xhr, requests;

before(function () {
    xhr = sinon.useFakeXMLHttpRequest();
    requests = [];
    xhr.onCreate = function (req) { requests.push(req); };
});

after(function () {
    // Like before we must clean up when tampering with globals.
    xhr.restore();
});

it("makes a GET request for todo items", function () {
    getTodos(42, sinon.spy());

    assert.equals(requests.length, 1);
    assert.match(requests[0].url, "/todo/42/items");
});

Or you can even mock a server

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

You can get very creative, Mocking timeouts, delays, 404's, 401's. Because you will still be using the JQuery.Ajax object library, while injecting spies that augment requests and responses, you can create more authentic and robust tests with less effort than if you had to stub all possibilities.

3 Comments

Thanks! I do use fake and mock server elsewhere in the code. For simpler tests, I just stub them away. Faster that way :)
@LimH., ahaa. In that case, my answer is unnecessary. Your need was just syntactical.
to be fair, the question was a bit badly written. I has nothing to do with stubbing in Sinon and everything to do with how jQuery has changes its export interface in 2.x :D But I really appreciate you taking the time to write your answer. And it does solve the problem although not in a way I was looking for ^ ^
0

You have a couple of choices to do requests in node:

1) With jquery

var $ = require('jquery')(require("jsdom").jsdom().parentWindow);
// now $.ajax works well

2) With npm request https://www.npmjs.com/package/request

3) Using native object XHR

I test these three options and finally I used package request (to avoid extra packages like jquery + jsdom) and for strange cases native XHR.

1 Comment

Hey thanks but I am testing client code using tools that run on node. I am not testing server code. Also your choice 1 is wrong. please read the question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.