Node.js support in Visual Studio

Unit testing Node.js in Visual Studio

Unit testing Node.js in Visual Studio

This is a multi-part post. Please see the following for background:
Node.js Support in Visual Studio
Setup Visual Studio for Node.js

The source for this project is located in my GitHub repository.

Unit testing is a critical skill in software development. Visual Studio has great support for unit testing in the Node.js plugin. We will be using Mocha for running tests.

Install Mocha

You need to create a default console Node.js application as described in my previous post Setup Visual Studio for Node.js.

  1. Open the pacakage.config file
  2. Add Mocha as developer dependency by updating file seen below
  1. Notice that you get auto-completion for the packages
  2. Save the file
  3. Compile the project (CTRL+SHIFT+B)

You’ll see the Mocha module on the node_modules folder.
Mocha in node_modules

Add a task to run tests

  1. Open the package.config file
  2. Add two script tasks as shown below
  1. Running the test task will fail because there are no test.

Add a class to test

For this example, we’ll do something very common. Create a class and test it. 🙂

  1. Create a folder named scripts containing a file named Simple.js
  2. Add the following code to the file. The code should be easy to understand.

Add your first test class

  1. Create a folder named test containing a file named simple.test.js
  2. Add the following code to the file

The documentation for Mocha explains all this. The key points are the “assert” statements. These should be easy to understand. Everything should look this this:

Simple File Structure

Run the tests

  1. Open the Task Runner Explorer
  2. Right click on test and select run

You can see that all the test ran and passed. You should change the Simple.js to intentionally break the test. For example change:

to

I make this mistake all the time… I think it’s to font I use… or my aging eye-sight. If you do this you’ll get the following output:

Watching your code and running tests.

Mocha has a great function to automatically run your tests when any of your files change. In C# there’s a tool named NCrunch which does the same thing.

  1. Run the “watch” task from the Task Explorer
  2. If all your tests pass, you’ll see the following

This gives everything you need to do unit testing Node.js in Visual Studio. I hope you’ve found it useful. Please contact me if you have any questions. I love to talk software.

Share this Post