Using Sinon’s FakeServer in QUnit test Setup and Teardown

I’ve recently begun switching from Buster.js to QUnit for my GitJs project and I discovered a roadblock when it came to using Sinon’s FakeServer in QUnit’s setup and teardown methods in a module. According to a blog post on Christian Johansen’s website, to use the fakeServer object you do something like this:

test("should make request", function () {
    var server = this.sandbox.useFakeServer();
    var dataSource = new XHRDataSource();
    dataSource.get();

    equal(1, server.requests.length);
});

You instantiate the fakeServer object using this.sandbox.useFakeServer. This totally works for an individual test. But what if you wanted to use the same fakeServer instance across all your tests in a module? Well, you’d think you’d just do this:

module('My Test Module', {
    setup: function() {
        this.server = this.sandbox.useFakeServer();
    },
    teardown: function() {
        this.server.restore();

        delete this.server;
    }
});

test("should make request", function () {
    var dataSource = new XHRDataSource();
    dataSource.get();

    equal(1, this.server.requests.length);
});

But when you run this you’ll get an error message about not being able to call useFakeServer because sandbox is undefined. After doing a little digging, I figured out that you actually need to reference the sinon object directly in order to use fakeServer in setup and teardown:

module('My Test Module', {
    setup: function() {
        this.server = sinon.fakeServer.create();
    },
    teardown: function() {
        this.server.restore();

        delete this.server;
    }
});

test("should make request", function () {
    var dataSource = new XHRDataSource();
    dataSource.get();

    equal(1, this.server.requests.length);
});

By calling sinon.fakeServer.create() and storing the instance as a property of this, you’ll be able to reference it in every test in a module without having to redeclare it.