Skip to main content

Using MockJax with QUnit

In this post, it is shown how the JQuery MockJax plugin can be used to mock an Ajax request within a QUnit test. The content seen here is an extension of the work shown in the JavaScript Unit Testing with QUnit post.

Below is the user.js  file containing the getAllUsers function which calls the GetAllUsers method on the API. This is the method that we want to mock in the new unit test.


The QUnit test is a bit more complex compared to the one written in the previous post. Firstly, the variable done is set to assert.async() which pauses the processing of the test until done() is called. Next, the mock is setup for the "api/GetAllUsers" Ajax request using Mjaxockjax. We define the url, content type, the type of request then finally the response that will be generated when the request is called.


The getAllUsers function is called and the returned data is passed into an assert.deepEqual, along with the expected result and the success message. Deep equal is very similar to equal (as seen in the previous post), however deep equal is used for comparing objects. Subsequently, done() is called.

Finally, we need to update the tests.html file. The Mockjax script and jquery is added into the head, the user and userTest JavaScript files are added into the body.



Now tests.html can be opened in a web browser and we can see both of the tests have successfully passed.


Comments