Run Unit Tests in Visual Studio Code with Keyboard Shortcut

Learn how to run unit tests in Visual Studio Code with ease. Follow my guide on setting up a Gulp task and flagging it as a test task using a keyboard shortcut.

In my last post I showed how I set up Visual Studio Code to support debugging a Yeoman generator to easily stub out a Node.js web server locally that can serve HTTPS requests: generator-nodehttps.

In this post I want to show how you can trigger all your unit tests to get run using a keyboard shortcut in Visual Studio Code as well. I’m implementing this by setting up a task using Gulp and then making VSCode aware of the task, but flagging that task as a test task.

Set up a Gulp Task

Gulp is a open source task runner build on Node.js… you can think of it like Microsoft’s MSBuild which lets you run tasks defined in XML. Gulp on the other hand lets you stream files and you author your tasks using JavaScript.

While you can install it globally using npm install -g gulp, I prefer to add it to just my current project. First make sure you have a package.json file in the root of your project… if you don’t just run npm init and answer a few questions to get one created.

Then install Gulp as a dev dependency which means it won’t be downloaded when you deploy your app in a production sense. Do this by running npm install gulp --save-dev. Because I’m also using mocha to run my tests I also have the gulp plugin gulp-mocha to run my tests… you can look at the package.json in the generator-nodehttps to see what else I’m using.

Now that you have that set up, create the task by creating a gulpfile.js in the root and adding the following code. This assumes your tests are all in a folder named test in the root of your project:

Set up VSCode to run Tasks

Now that you have the Gulp task set up, you can set up VSCode. Within VSCode, hit SHIFT + CMD + P , type task and pick Task: Configure Task Runner. This will create a .settings / tasks.json file with a bunch of default code. Replace it with the following. This tells VSCode that you have Gulp tasks, specifically there’s one named run-tests and it’s a test command.

Now, when you’re in VSCode, you can press SHIFT + CMD + T or use the command Tasks: Run Test Task and it will execute your tests within the output window in VSCode that looks like so:

Running tests in VS Code

Running tests in VS Code

Pretty slick!

Andrew Connell
Developer & Chief Course Artisan, Voitanos LLC. | Microsoft MVP
Written by Andrew Connell

Andrew Connell is a full stack developer who focuses on Microsoft Azure & Microsoft 365. He’s a 20+ year recipient of Microsoft’s MVP award and has helped thousands of developers through the various courses he’s authored & taught. Andrew’s mission is to help web developers become experts in the Microsoft 365 ecosystem, so they can become irreplaceable in their organization.

Share & Comment