Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock data in javascript unit testing ?

I m using Jasmine library for unit testing my javascript code. I have tried to find a way to mock data, but I didn't found a good solution. Information on how to mock data and libraries which mock data automatically with an example would help me a lot. Thanks in advance.

like image 590
Srikanth Darmapuri Avatar asked Aug 05 '26 18:08

Srikanth Darmapuri


1 Answers

Sinon.js is a generic, framework-agnostic library that enables you to mock entirely data in the browser (by faking XMLHttpRequest Object). You can use it with jasmine e.g. this way. What this library does is extending jasmine assertions with native sinon features, such as called, threw, returned, etc. See them all here.

In Sinon, you should take a look at fakeServer.

Additionally, here you've got a working example of sinon's fakeServer along with jasmine runner written by the author of Sinon.js: https://gist.github.com/cjohansen/739589 :)

And an in-depth introdution to AJAX/sinon: http://tutorials.jumpstartlab.com/projects/javascript/testing/2-ajax-and-sinon.html

like image 56
ducin Avatar answered Aug 07 '26 08:08

ducin