JavaScript Code Coverage using Karma-Coverage w/ Grunt

As part of our ongoing effort at my client to setup a testing environment for our JavaScript code I wanted to also setup the ability to do code coverage on our files.

To accomplish this I am going to integrate istanbul coverage reporting w/ our karma test runner via the karma-coverage plugin.

** I am going to assume you already have JS tests running w/ Karma and Grunt **

To accomplish this we first need to install the following NPM packages

  • npm install istanbul –save-dev
  • npm install karma-coverage –save-dev

Next thing we need to do is open our karma.conf.js file and make some changes to it.
1) Update the reporters configuration

reporters: ['progress', 'coverage'],



2) Add a preprocessor section to the configuration.

    preprocessors: {
        // source files, that you wanna generate coverage for
        // do not include tests or libraries
        // (these files will be instrumented by Istanbul)
        '**/js/page/**/*.js': ['coverage']
    },


3) Setup the coverage reporter. This is the outputted format of the results.

    coverageReporter: {        
        dir: '../../../grunt/js.coverage/',
        reporters: [
                { type: 'html', subdir: 'report-html' },                
                { type: 'teamcity', subdir: '.', file: 'teamcity.txt' },
        ]
    },



In my setup I am doing 2 things.

  • I am placing my coverage files inside my grunt working directory. This means I need to back navigate to the folder.
  • I am outputting to both HTML and teamcity format. You do not need to specify more than one format if you do not want or need to.



3) I added the karma-coverage plugin to the plugin section. When I left this out I would get an error, adding this resolved the missing plugin error.

   plugins: [
      'karma-phantomjs-launcher',
      'karma-jasmine-jquery',
      'karma-jasmine',
      'karma-coverage',
    ],


After you have made the following changes you should be able to run karma via grunt as you normally would and boom, you have code coverage for you Jasmine JavaScript files.

Till next time,

Posted in Grunt, Jasmine, Testing | Leave a comment

Forcing MVC Model State to invalid for Unit Tests

Unit testing ASP.Net MVC applications is easier than every today. But how do you force ModelState.IsValid to be false in a unit tests?

The simple thought would be to simply create an invalid object and pass that into your action method, but this will not work. Why? Because the validation is down by the MVC pipeline prior to reaching your actual method and you do not have direct access to this.

However, we can fake it by manually adding model errors, thus getting IsValid to return false.

Imagine you have a controller which does something like below

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CustomerFeedback(CustomerFeedbackData model)
{
    if (!ModelState.IsValid)
    {
        return Json(new ResponseModel<CustomerFeedbackData>());
    }

    emailService.CustomerFeedback(model);

    return Json(new ResponseModel<CustomerFeedbackData>(model));
}

And you wanted to create a unit test that would exercise the failing of the .IsValid check.

To accomplish this you could manually force a model error like below.

[Test]
public void CustomerFeedback_When_Model_Is_Not_Valid_Will_Return_Error_State()
{
    var controller = GetController();  // helper method to construct an instance of the controller
    var customerFeedbackData = new CustomerFeedbackData();

    // force validation error --> this is the magic sauce
    controller.ModelState.AddModelError("FirstName", "First Name is Required");

    var result = (JsonResult) controller.CustomerFeedback(customerFeedbackData);

    var asModel = (ResponseModel<CustomerFeedbackData>) result.Data;

    asModel.Success.ShouldBeFalse();
}

Long story short, you can force errors by adding them to the ModelState instance on the controller.

Till next time,

Posted in MVC | 3 Comments

Software components as a toy

For kids Christmas has a lot to do with toys. Looking forward to new ways to play. For me an as elder kid who still enjoys to toy around, aka as a software engineer, I want to reflect on the analogy between software components and certain toys.

Well organized software is build from components. Quite often the components have been compared to Lego blocks. Toys for kids aged 0 to 99, to quote their own advertorials. A Lego block is simple and has a clear interface to connect it to other blocks.

Lego

Compared to the simplicity of the interface the number of ways to connect blocks together is big. Leading to an endless amount of creatable structures.

maxresdefault

(Helicopter story here)

Over the years the line of Lego products has adapted to popular demand. A lot of sets pre-fantasized to a specific movie or game were thrown on the market. These sets contain more and more building blocks which are very different from the original simple blocks.

 

(Yes Minecraft)lego_tool_no_3_1

The blocks have no more possibilities than just to be stacked on top of the rest, with no more interfaces to connect it to anything else.

Lego is not the only construction toy. In my youth Meccano was also very popular. Metal parts put together using nuts and bolts. We built cars, steam engines, cranes and the like.

dd102270-891b-012c-d1ec-0050569439b1

Meccano suffered the same problem as the later Lego blocks. Basic parts were quite simple, but for building more complex things you needed an ever increasing array of specialized parts.

9c1f98c0-0c88-012f-b0cc-0050569439b1

Mecano was not the only brand offering metal construction kits. I had the luck to have Trix Express, handed down by my father.

trix

Trix was basically different. The Meccano strips have one row of holes. All Trix parts have three in paralel. Organized in such way that the holes make even triangles.

Trix unité A

With two nuts you firmly join two strips in an angle of 0, 45 or 90  degrees. And thus you can create almost each complex construction from a very limited number of different parts.

Giant Blocksetter Crane

The only limit on whatever you were building was the amount of pocket money or Santa Claus (Sinterklaas)

To finish of with a look into the new year: what do your software components look like, Meccano or Trix ?

Happy constructing

Posted in Uncategorized | 1 Comment

Norfolk.js Turns One Year Old

Norfolk.js just celebrated its first birthday in November!

Norfolk.js is Hampton Roads’ JavaScript developer user group. It was founded in Norfolk, Virginia, by small group developers and has grown to nearly 200 members are from all over the area. The goal of this user group is to create the most accessible way possible for local developers to meet to discuss all things related to JavaScript. In 2015, we hope to continue the momentum of the group by focusing on topics of particular interest to our members.

Norfolk.js has been a tremendous experience and a bigger success than I, or any of the other organizers, could have imagined. The success of of Norfolk.js isn’t just due to the dedication of any one of us, but because of support of our entire local development community. The financial and logistical support from local sponsors (like CodeBetter.com) also allows us to deliver a quality experience that rivals groups in larger cities. We’ve been able to learn from  existing user groups like 757.rb and HRNUG, and get feedback from our peers about what works for them in a developer user group. We open-sourced our website and our organizing discussions, and use Github to facilitate this valuable feedback and to make Norfolk.js as inclusive as possible.

Over the last year we’ve hosted some of the best developers in the local area and have had visits from some amazing out-of-town JavaScripters, like Chris Williams and Mike McNeil. We’ve also hosted special events like International NodeBots Day and Worldwide Meteor Day. We typically meet on the third Monday of each month to eat, drink, socialize, and listen to an interactive talk. Every four months, we have a social meetup, Beer.js, at a local pub or brewery. This month, we welcomed Hiro Asari from Chapel Hill, NC to discuss unit testing and continuous integration with Travis-CI. In February, we will be partnering with the Chrysler Museum for the first time to host our meetup in their museum space and get a private viewing of their “Art of Video Games” exhibit.

Norfolk.js has provided a way for our members to meet new people and try new JavaScript-related technologies that might have otherwise been unavailable in this area.

We are always happy to welcome new speakers, sponsors, and members. Contact one of our organizers if you’d like to get involved. To get a list of our upcoming events, please see our events page.

Posted in Uncategorized | Leave a comment

Now Witness the Power of a Fully Operational CodeBetter Scholarship!

The CodeBetter Endowed Scholarship was a $25,000 commitment over 5 years to help provide financial support for female undergraduate students in computer science.  It’s one of our efforts to try to chip away at the current gender disparity in our field.  I’m happy to announce  that we’ve reached our goal! I just received this email from the director of donor affairs at Old Dominion University, where we established the CodeBetter endowed scholarship.

With the $500 payment just received, the endowment is fully funded. The endowment will produce an award for the 2016-2017 academic year.

The way this whole process works has been really interesting to me.  Once the scholarship is funded, the return on its investments produce an award.  In this way, it will outlive all of us – that’s a powerful idea to me.

It took us a few years of continuous funding. In fact, we’ve been sending a check for $500/month over the past 5 years.  This is roughly 70-80% of our total ad revenue. We’ve also been putting in extra every month so that we can support a student while we have been funding the endowment. And I’m happy to report that our first recipient is about to graduate this month with her BS in computer science.  Congratulations to Banita!

So, now that that is done, I’ve been making some more local commitments so that CodeBetter can continue to support developers.  One is to provide some monthly funding for the local .js group here in VA (in fact, one of the group’s leaders, Linda Nichols, is soon to start blogging with us).  Another is to provide support for the local Code for America brigade.  We are going to continue to support our community…  Have a need?  Get in touch and pitch it to us.

Posted in Uncategorized | Leave a comment