Showing posts with label Jasmine. Show all posts
Showing posts with label Jasmine. Show all posts

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.


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...