简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM