Velidan
Velidan

Reputation: 6019

Jasmine how to mock http request (for fetch and XMLXtthpRequest)

I want to test some ajax function that makes a request to the some url. I tried to use nock to mock http but it it's working because I use Karma runner and it throws to me an error about "can't find module 'fs'". It is because karma run tests on the browser.

How I can do that ? Thanks (I tried jasmine-ajax but it's also isn't working somehow).

As I understand an issue appears because karma works in the browser. But how I can fight with that.

Thanks for any help!

Upvotes: 0

Views: 1908

Answers (1)

xmike
xmike

Reputation: 1038

jasmine-ajax surely does work. here is a sample from working code (jasmine over karma):

describe('RequesterTest', function(){

    beforeEach(function(){
       jasmine.Ajax.install(); // this enables interception
    });

    afterEach(function(){
        jasmine.Ajax.uninstall(); // disables interceptions
    })

    it('makes $.ajax', function(){
        spyOn($, 'ajax');
        $.ajax({url: 'http://example.com'});
        expect($.ajax).toHaveBeenCalled();
    });

    it('assert success callback for ajax', function(){
        spyOn($, 'ajax');
        var myCallback = function(){};
        $.ajax({url: 'http://example.com', success: myCallback});
        var actualAjaxOptions = $.ajax.calls.mostRecent().args[0];
        expect(actualAjaxOptions).toEqual(jasmine.objectContaining({
            success: myCallback,
        }));
    });
});

exapmle assumes jquery defined globally and no modules/AMD usage.

Upvotes: 1

Related Questions