Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tool to easily mock restful service [closed]

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.

like image 979
blue123 Avatar asked Dec 26 '12 05:12

blue123


3 Answers

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/

like image 169
NullRef Avatar answered Oct 20 '22 06:10

NullRef


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
}
like image 33
rai.skumar Avatar answered Oct 20 '22 07:10

rai.skumar


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"}
// ]
like image 34
François Zaninotto Avatar answered Oct 20 '22 08:10

François Zaninotto