Book Image

Knockout.JS Essentials

Book Image

Knockout.JS Essentials

Overview of this book

Table of Contents (16 chapters)
KnockoutJS Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Using Mockjax to mock HTTP requests


Mocking data just means replacing the $.ajax calls with another function that emulates its behavior. Mocking is a commonly-used technique when following a test-driven development paradigm.

To mock jQuery AJAX calls, we are going to use a library called Mockjax. To install Mockjax in the application, follow these steps:

  1. Download the library from https://github.com/jakerella/jquery-mockjax.

  2. Save it into the vendors folder.

  3. Add a reference in the index.html page, just after the jQuery library. To do this, use the <script> tag, as shown here:

    <script type='text/javascript' src='vendors/jquery.mockjax.js'></script>
  4. Create a folder called mocks and create a product.js file inside it.

  5. In the product.js file, define a mock calling the $.mockjax function, as follows:

    $.mockjax({
      url: '/products',
      type: 'GET',
      dataType: 'json',
      responseTime: 750,
      responseText: []
    });

    In this definition, you are mocking the request called inside the ProducResource...