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.
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/
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
}
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"}
// ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With