Last Updated: September 29, 2021
·
2.067K
· craigmaslowski

FakeServer - Simplified Jasmine/Sinon interface for Ajax mocking

FakeServer is a bridge between Jasmine and Sinon. It provides a simplified interface for mocking ajax requests.

https://github.com/craigmaslowski/FakeServer

// Create the fake server
var server = new FakeServer();

// Setup routes
server.routes([
    {
        url: '/myRoute',
        headers: {
            'Content-Type': 'text/html',
            'Custom-Header': 'Custom-Header-Value'
        },
        body: '<p>some html</p>'
    }
]);

describe('myRoute', function () {
    var response, jqXHR;

    beforeEach(function () {
        $.ajax({
            url: '/myRoute',
            success: function (resp, textStatus, jqxhr) {
                response = resp;
                jqXHR = jqxhr;

                // let FakeServer know the
                // ajax call is complete
                server.complete();
            },
            error: {
                jqXHR = jqxhr;

                // let FakeServer know the
                // ajax call is complete
                server.complete();
            }
        });
    });

    afterEach(function () {
        response = undefined;
        jqXHR = undefined;
    });

    it('should return some html', function () {
        // Test the response once
        // the ajax call is completed
        server.respond(function () {
            expect(response).toBe('<p>some html</p>');
        });
    });
});

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside