mockjax equivalent in jest or plain JS Unit Test Library (eg. Karma Jasmine )

220 views Asked by At

Greetings want a very basic unit test for some of the ajax requests of my application. http://jsfiddle.net/Orbifold/sqdzzvey/

I want to know what you use to mock endpoints in your applications like it is done here:

$.mockjax({
    url: "/orbifold/api",
    responseTime: 3000,
    responseText: {
        "version": "2.3.15" 
    }
});

I would like to have the same behavior without the need for jQuery but plain js. I would like result equivalent in any other framework. Please attach a working fiddle. I am not sure if this is possible or can only be done with qunit so please enlighten me.

1

There are 1 answers

0
Jordan Kasper On

I would recommend using Sinon if you don't want to include jQuery. You can create "fake servers" that will perform very similar functionality (although there is a little less automation of some things):

Probably in some SETUP method...

const server = sinon.createFakeServer();
server.autoRespond = true;

And in your TEST...

server.respondWith(
  "GET",
  "/orbifold/api",
  [200, { "X-some-header": "foobar" }, '{"version": "2.3.15"}']
);

// now run your code that makes an ajax call

// then do your assertions/callbacks/etc

Then in your TEARDOWN method...

server.restore();