7

Is there a tool to easily mock restful service so that we could test our Ajax calls easily?

For example, I need to mock a restful service to return string in JSON or XML format.

Pankit Kapadia
  • 1,579
  • 13
  • 25
blue123
  • 2,937
  • 7
  • 27
  • 29

4 Answers4

2

You might give jasmine-Ajax a shot. https://github.com/pivotal/jasmine-ajax

Of course it means you need to test with Jasmine. https://github.com/jasmine/jasmine/

Sinon is a very powerful mocking library as well. http://sinonjs.org/ and you can choose your test framework. I have used it with Mocha. http://visionmedia.github.com/mocha/

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
NullRef
  • 3,713
  • 1
  • 20
  • 18
2

Try jmockit ; i had used it for mocking a web service. But this is a Java solution. If you want to mock REST API at server side then this will fit. This will not help if you don't own REST application.

If you want to mock at client side(in JS) itself;

You can write your own mocking framework/interface. So when you send a request put a layer in-between which can just return you test response instead of actually calling the REST URL.

Client ---> Mocking Interface---> REST API CALL

function mockingInterface(var url){
    //if original
    //make REST call

    //else; return mocked data
}
Ivaylo Slavov
  • 8,839
  • 12
  • 65
  • 108
rai.skumar
  • 10,309
  • 6
  • 39
  • 55
2

FakeRest does exactly what you want.

// initialize fake REST server and data
var restServer = new FakeRest.Server();
restServer.init({
    'authors': [
        { id: 0, first_name: 'Leo', last_name: 'Tolstoi' },
        { id: 1, first_name: 'Jane', last_name: 'Austen' }
    ],
    'books': [
        { id: 0, author_id: 0, title: 'Anna Karenina' },
        { id: 1, author_id: 0, title: 'War and Peace' },
        { id: 2, author_id: 1, title: 'Pride and Prejudice' },
        { id: 3, author_id: 1, title: 'Sense and Sensibility' }
    ]
});
// use sinon.js to monkey-patch XmlHttpRequest
var server = sinon.fakeServer.create();
server.respondWith(restServer.getHandler());

// Now query the fake REST server
var req = new XMLHttpRequest();
req.open("GET", "/authors", false);
req.send(null);
console.log(req.responseText);
// [
//    {"id":0,"first_name":"Leo","last_name":"Tolstoi"},
//    {"id":1,"first_name":"Jane","last_name":"Austen"}
// ]
François Zaninotto
  • 7,068
  • 2
  • 35
  • 56
0

You can try http://apiary.io/ too.

There you can define the request responses in text format, so in JSON for example. Advantage is that the MOCK API is public so any part of the team can use it.

fmelan
  • 127
  • 1
  • 5