Jasmine tests for jquery post

Jasmine is a js framework that allows behaviour driven testing of Javascript components. One challenge I ran into was how to setup the tests in order to mock jQuery.post(…) calls.

An example of the code for making the call is:

So, how do you test this and validate the correct url & data was used?

First, you need to spy on the ajax call:

The interesting thing to note, even though you are calling $.post, you need to spy on $.ajax
If you want to force the .fail() state of the code then you can use d.reject(). See http://api.jquery.com/category/deferred-object/ for more alternatives.

When you then verify the valid behaviour, you can check eg:

Moq – the basics

During a recent XP programming course we made use of the Moq’ing framework. I’d not used this before so tried to come up with some example moq basic tests. There are several tutorials on the internet which offer up the basics so do hunt around. Hopefully the following provides some simple examples for people to get started with.

The following code relies on the following assemblies:

The real crux of TDD is that you program your functionality to interfaces – here we have a simple interface and dto:

Note the importance of the virtual property in MyObject will be highlighted in the tests. In the following examples not all the tests pass – this is intentional! Failing tests are included to demonstrate specific features of Moq. Apologies for the long dump of test code – the idea is really to copy it into a test class and let NUnit do the work.

Here is the expected results when evaluated in NUnit: