Monday, April 18, 2016

Unit testing with Jasmine in ASP.NET MVC

In this example we are going to create unit tests using the Jasmine framework in a MVC Application.

The technology we will be using:
  • Visual Studio 2013
  • ASP.NET MVC 5.0
  • Jasmine Test Framework (JasmineTest) 2.2.0
The full example can be found on github (https://github.com/rbercocano/MVC-Jasmine)


What is Jasmine?

Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.


You can find more information on http://jasmine.github.io/


Pre Requisite

It's important to note that using external javascript files is kind of a requirement. Besides that it's also a highly recommended practice.


Step #1 - Create the MVC Project

In this example we will need a simple MVC Project, no authentication is required.



Step #2 - Install Jasmine package

Now we need to install the JasmineTest Framework to create the unit tests. Let`s do it using the NuGet package manager.





It will automatically create a JasmineController and also a View (SpecRunner) to execute and show the test results.


Step #3 - Change the default route

Now let`s change the default application route to make the JasmineController be called as default route.


    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Jasmine", action = "Run", id = UrlParameter.Optional }
            );
        }
    }

Step #4 - Create a new Controller

Now we will create a new Controller with two basic actions.


public class MathController : Controller
    {
        // GET: Math
        public JsonResult Sum(decimal x, decimal y)
        {
            return Json(x + y, JsonRequestBehavior.AllowGet);
        }
        public JsonResult Multiply(decimal x, decimal y)
        {
            return Json(x * y, JsonRequestBehavior.AllowGet);
        }
    }

Step #5 - Create the javascript file

Now we will create a simple javascript file with two functions to call the MathController actions. These scripts will be tested by Jasmine.
Create a javascript file named math-service.js and place it inside the Scripts folder.
Now we will create the functions to call the MathController actions. This is shown in the following code.


"use-strict";
var math = {
    sum: function (x, y) {
        var result;
        $.ajax({
            type: "GET",
            url: 'http://localhost:14489/Math/Sum',
            data: { x: x, y: y },
            async: false,
            success: function (response) {
                result = response;
            }
        });
        return result;
    },
    multiply: function (x, y) {
        var result;
        $.ajax({
            type: "GET",
            url: 'http://localhost:14489/Math/Multiply',
            data: { x: x, y: y },
            async: false,
            success: function (response) {
                result = response;
            }
        });
        return result;
    }
}

Step #6 - Create the unit file

Now we will create the unit test using Jasmine.
To do it create a folder called tests inside the Scripts folder.
Create a javascript file called math-spec.js.
Now we need to create the tests. This is shown in the following code.


describe("Math - Calling MathController using ajax calls", function () {
    describe("Sum", function () {
        it("should return 9", function () {
            expect(math.sum(2, 7)).toEqual(9);
        });
    });
    describe("Multiply", function () {
        it("should return 25", function () {
            expect(math.multiply(5, 5)).toEqual(25);
        });
    });
});

Step #7 - Add reference to your tests

Now that we have everything done all that is left to do now is adding our new test file and its dependencies to the test runner view. Open the SpecRunner.cshtml file found in Views > Jasmine and add 2 more script includes in the head part of the view.


<script src="~/Scripts/math-service.js"></script>
<script src="~/Scripts/tests/math-spec.js"></script>

Step #7 - Run the tests

Now we just need to Run the application and see the test results.


7 comments:

  1. Hello Rodrigo,
    The Article on Unit testing with Jasmine in ASP.NET MVC is very informative. It give detail information about it .Thanks for Sharing the information on Unit Testing in .net Software Testing Company

    ReplyDelete
  2. is this still works? I can't find Jasmine packages in NuGet

    ReplyDelete
    Replies
    1. This is the link for the jasmine packages https://www.nuget.org/packages/jasmine/

      Delete
  3. Thanks for the post.

    Am new to jasmine. I have followed the steps which you mentioned, but am getting $ is not defined. am using MVC 5 Application.

    ReplyDelete
    Replies
    1. $ is probably jquery, you'll need to add that as a script tag somewhere in your test html file or elsewhere. You may also need to work out which version is compatible with your code for it all to hang together.

      Delete

Microservices – Creating Resilient Services

Dealing with unexpected failures is one of the hardest problems to solve, especially in a distributed system . A microservice needs to...