Unit Testing JavaScript with Gulp and Mocha

Immediately after getting my first node project up and running, I started to ask how do I write and test my code?  My corporate experience has taught me the importance of automated testing, how to create them in C# with visual studio and how to automate the testing with TFS, but node and VS Code is totally different.  Visual Studio is an IDE and it will take care of almost everything for you.  You simply need to create a new project (a ‘test’ project) in you code and you are good to start writing tests.  Executing your test is as easy as a file menu click or a key board short cut.  You don’t have to think about the testing framework, how your code is built or executed because the IDE will take care of that for you.
Testing Framework
First question to answer was what does it take to write a unit test with JavaScript?  After asking around on Google I discovered node packages, mocha and should.  These libraries allow you to write simple and human readable tests.  In JavaScript, you don’t get classes per say, you need to think in terms of functions and prototypes.  In MS Test you typically create a test class that maps to one class in your code, the target class.  This thinking needs to evolve with JavaScript into files and functions.  One test file is used to test one file of code and you use functions, not classes, to define your tests.  With mocha there are two very interesting functions you need to know about, ‘describe’ and ‘it’.  When you see ‘describe’ think test class in MS Test.  Describe creates a container and label for your tests.  Now ‘it’ is the actual test, think a test method in MS Test.  The ‘it’ function needs a name and a function to execute.  The should package is what will help you make your tests more readable.  This package is similar to the NuGet package, Fluent Assertions.  It allows you replace robotic assert statements with more fluent and readable asserts.  In my experience of training interns, this fluent syntax goes a long way to help new people understand unit testing and understand what is actually going on in the tests.1
Testing Framework
First question to answer was what does it take to write a unit test with JavaScript?  After asking around on Google I discovered node packages, mocha and should.  These libraries allow you to write simple and human readable tests.  In JavaScript, you don’t get classes per say, you need to think in terms of functions and prototypes.  In MS Test you typically create a test class that maps to one class in your code, the target class.  This thinking needs to evolve with JavaScript into files and functions.  One test file is used to test one file of code and you use functions, not classes, to define your tests.  With mocha there are two very interesting functions you need to know about, ‘describe’ and ‘it’.  When you see ‘describe’ think test class in MS Test.  Describe creates a container and label for your tests.  Now ‘it’ is the actual test, think a test method in MS Test.  The ‘it’ function needs a name and a function to execute.  The should package is what will help you make your tests more readable.  This package is similar to the NuGet package, Fluent Assertions.  It allows you replace robotic assert statements with more fluent and readable asserts.  In my experience of training interns, this fluent syntax goes a long way to help new people understand unit testing and understand what is actually going on in the tests.
2 3
Once you have these in place you can run your tests with the test command in the command pallet or the keyboard shortcut.
4

Getting Started with Node

Recently I attended Microsoft’s Build conference in San Francisco.  Prior to the conference I had heard about Visual Studio Code and had starting fiddling around with it and MVC Core on Linux.  While I was there I had the opportunity to explore a few sessions and labs related to VS Code and Node.js.  Over my career I have learned many techniques for building quality into software products (such as: code reviews, unit testing, automated builds, etc.) and I have also accepted that when it comes to the user interface (i.e. JavaScript in my world) those practices either do not apply or are too time consuming to be worth pursuing.  As a result, I have formed a basised opinion and do not see any reason why a sane developer would ever choose to use JavaScript as a server side programming language.   And yet, they are and, Microsoft is promoted it.  What?  Why?  I have realized that I am missing something.  This blog series is documentation of how I’m exploring what I’m failing to understand, at the moment.
This first post will be very short because Microsoft has already done a good job of writing it 🙂  The first step in learning any new tool/framework/language is simply saying “hello” or more specifically, “hello world.”  Microsoft has provided an excellent tutorial for getting up and running with Node.

 

npm install -g express-generator
express ExpressApp
cd ExpressApp
npm install
You are then free to write in a hello world message…
image1
you can then fire up the debugger and point a browser to http://localhost:3000 to see the hello world
image2
From here I added in boot strap into the views and put together a nice starting point to branch out into future learnings.  You can see what I have done on my GitHub.

Dependency Injection and ASP.NET MVC

For many years I have used Dependency Injection in the projects I have worked on professionally.  At work we have standardized on Microsoft’s Unity package.  Unity is great; I have nothing against it, but I wanted to learn more about how these IoC packages work under the hood and the dependency injection really takes.  Turns out, with C#, it really doesn’t take much.  The .NET framework includes reflection and allows you to dynamically create objects without much effort.  To build an object, all you need to do is reflect into the constructors, pick one to use (in my case I did a greedy search finding the largest constructor I could use) and build the object.  You have to recursively build the parameters to the constructor.  Because recursion is happening, it doesn’t matter how complex you object is, it can have zero or a hundred constructor parameters, and each parameter can have their own dependencies.  Recursion makes for a simple and elegant solution.
My next challenge, and this is something that I have used at work many times, was to make this work in the MVC framework.  MVC relies on reflection and naming convention to build your controller objects with the HTTP requests, but the magic is that MVC knows exactly where to send the request and how to build the controller object it needs.  But, have you ever said, gee, I really need a database connection in this controller, so I’ll just add it to the constructor because that will make testing really easy.  MVC will puke on you because it is also using a dependency injection tool under the hood, a very very simple one and only builds parameter-less constructors.  Good news, almost every piece (at least everything I have ever worked with) of MVC is extendable, including its simple DI code.  MVC defines the IDependencyResolver interface for resolving dependencies, including controllers.

I hear this all the time

I recently an email from the Big Brothers Big Sisters of the Ozarks.  In case you don’t know, there is a shortage of willing big brothers to be good mentors and role models to the boys in the program.  In it, they identified one of the main reasons why men don’t volunteer is that “[they] have never been asked.”  Well, count this as me asking the men out there to step up, volunteer, and be a good mentor and role model to these children.  Poverty is a real, and often overlooked, problem in our community.  For the city of Springfield over 25% of this residents live below the poverty line, and it is even worse for our children.  For the Springfield public schools, over 50% (yes half) of the students qualify the free and reduced lunch program.  Don’t think that the surrounding communities fair much better.  For Nixa, 30%, for Ozark 30%, for Republic 37%, for Rogersville 30%, for Strafford 30%, for Willard 34%, of the high school students qualify for free and reduce lunches.  Those numbers are just for the high schools, the elementary and middle schools (and the districts as a whole) are higher.  In my life, education is what has opened up opportunities for me and it is education that will help reduce and eliminate the poverty problems that we have in our region.  Littles that go through the mentoring program are less likely to skip school, more likely to graduate high school and more likely to attend college.  I have the privilege of working for any employer that values helping the local communities that is has a presence in and backs that value up with corporate charitable giving and by encouraging employees to participate in an annual United Way payroll deduction.  Concern for Community is one the seven cooperative principles.  I will tell you that these things alone are not enough to solve the problems facing our community.  If they were, our community’s poverty rates would not be worse than state averages.  I would like to ask you to read the attached letter from the Big Brothers Big Sisters of the Ozarks; then, I would ask you to join me in helping make this community better for the next generation.

 

I hear this all the time

Learning Friday: Entity Framework 7

ah… scratch that, Entity Framework Core 1.0
Recently, one of my peers and I were tasked with creating a database to help us select and identify the different technical skills (PowerShell vs C# vs ASP, etc) that we expect our team members to have as they progress through the technical career track.  Anyway, the details of the exercise are very uninteresting, but what is interesting is that I was able to use this as a chance to explore Entity Framework 7 Entity Framework Core and as a chance to share what I learned with most of the developers in my organization.
Entity Framework 7 Entity Framework Core recently hit release candidate status and there have been some serious changes under the hood to how this ORM works.  Entity Framework has always been build around the EDMX for creating the model to map between you code and the database.  In Entity Frame work the concept of the “Code First” model was introduced to eliminated the need for using the XML based model files and allow developers to build their models using code only.  This code first approach still relied on all the EDM bits inside Entity Framework to actually work.  In EF7 EFC, that model has been retired and the code first method is the way to build your database models with all the EMD bits being left behind.

At Associated we have expectations that all of our people are leaders, to some degree, and that all team members will be effective communicators in both written and verbal communication skills.  It is an emphasis that I have not seen in other organizations but I have see first had the costs of poor communication insted time in meetings and failure to properly execute on projects.  So, to promote these skills, and to promote a culture of learning, we created the “Tech Faire” platform.  It started as an every other Friday activity where people gave 20-20 style pecha kucha style presentation over a work related (usually technical since this started in our development departments) subject.  I would be an opportunity to work on your communication and presentation skills and teach the rest of the department something.  Well, the Tech Faire has grown company wide and now it is happening on a much less frequent basis.  To continue promoting learning and nudging people to teaching others and growing their communication skills, I ran the first “Learning Friday” activity.  My idea is that these activity are 30 minute classes where you dive deeper into a technical subject that you would in the pecha kucha presentation.  It is my strong belief that our senior employees should be doing something like this to promote and grow our junior employees.  This Learning Friday platform is intended to fill the gaps between our Tech Faires and provide a new (smaller and less intimidating) platform to teach technical skills and grow communication abilities.

I used the exercise that I discussed above as a chance to explore Entity Framework 7.  Building as simple ASP.NET site that talked to a database (with EF7) took about 8 hours from zero to production ready, dependency injection, unit testing, the works.  I then spend about 1 hour stripping out the non-EF7 bits and grabbing some screen shots to create some documentation.  So for a total investment of 1 hour above what I was already asked todo, I had everything ready to share my knowledge about EF7 with our other developers.  My goal was to have 6 people (one from each development team) join me to explore EF7.  The results were amazing.  I had 18 people join in, almost all our developers and database administrators.  During this exercise I walked through created a database with Sql Server Data Tools and how easy it was to ship that to your local database and then ship SQL to our DBAs to create the database on a test/production environment.  Our DBA’s complained about some of the “junk” that the tool generates but they all agree it was a big improvement from “pasting sql into a word document.”  I then demonstrated how to generate a code first model from the existing database, a big concern in the room because EDMX is going away.  I then walked through unit testing with the in-memory database provider and configuration with with SQL provider.  All in all, there was about 1 man day invested in this learning.  For that cost we probably saved several man days of independent research and experimentation and we all gain a common starting point and understanding of EF7 and the code first design approach.  In my opinion, time well spent.  Below is the documentation I created for this exercise if you would like to see or following along your self.

Start with a web project, unit testing project and SSDT database project with your tables modeled.

Using SSDT to compare databases
Follow these steps to push you schema to a local database
Pushing Schema changes with SSDT
Steps for created an Entity Framework model
creating entity framework objects from existing database
Select code first (note I’m still using EF6 Power Tools)
creating entity framework objects from existing database
Here is your code first context.  Note the ModelCreating Method and the simple setup to identify Keys and no null colums.
Entity Framework OnModelCreating
This is our test context, it will use the In-memory provider, to keep the in-memory object available after the controller disposes the context I have overrode the dispose method.
Test implementation for entity framework
Here is our test fixture, not the use of “UseInMemoryDatabase”
Image
Entity Framework 7 is platform agnostic, so there is no concept of Schema or Identity columns, by adding the SQL Server extensions you can get those things into your context.
SQL Server configuration for Entity Framework
Finally, here is how you wire up your context to you connection string.
SQL Server configuration for entity framework