Testing asynchronous JavaScript

By making AJAX calls directly to the server from your JavaScript view-model it can be impossible to get the code under test. A simple solution is to fake the calls and make them synchronous.
This example view-model for a library takes a function that will make a call to the server to check out a book for a user.

When the page loads, the view-model will be set up with the actual jQuery function like so:


In the tests, the jQuery call can be faked out with one that returns a canned response:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s