Monthly Archives: July 2018

Vsts: setting up tests and coverage to run on build for Javascript projects

I’m currently writing Javascript code, React and Redux to be more specific. After picking up the brilliant book “Human Redux” I’ve really started to enjoy this ecosystem.

But, remembering the brilliant Zombie TDD I also want to get back in the testing-game. This is quite easy when using create-react-app, as Jest is a great tool.

However, this is not the topic of this post. The topic here is how to get Microsoft VSTS (Visual Studio Team Services) to run your tests during the build phase, and report test results and coverage, and provide you with stuff like this:

2018-07-25 10_14_11-Window

coverage

You need to do stuff both to your project, and to your vsts build definition.

First off, your project:

You need the jest-junit package

npm install jest-junit -S

And, you need to edit your package.json file. First, add the top-level entry “jest”, with the following content

"jest": {
    "coverageReporters": [
      "cobertura",
      "html"
    ]
  },

and the top-level entry “jest-junit”, with the following content

"jest-junit": {
    "suiteName": "jest tests",
    "output": "test/junit.xml",
    "classNameTemplate": "{classname} - {title}",
    "titleTemplate": "{classname} - {title}",
    "ancestorSeparator": " > ",
    "usePathForSuiteName": "true"
},

Finally, you need to add the task “test:ci” to your script-block:

"test:ci": "react-scripts test --env=jsdom --testResultsProcessor=\"jest-junit\" --coverage",

So, what have we done here?

  1. We set the coverage reporters of Istanbul (which jest uses) write both the cobertura and html formats
  2. We set up jest-junit to produce junit-xml from our tests
  3. We create a test-task to be run on vsts that uses these two

You also want to add the resulting files to .gitignore

# testing
/coverage
/test

This should now work locally, test it by running

CI=true npm run test:ci
The coverage-folder should be created and the file test/junit.xml should be created.

So, everyting is good on the project side, time to move on to vsts.

Create a build, and add three tasks:

The first is an “npm” task, configure it like this
npm_test

Then, you need to publish the results of the test and the coverage, so add a

“Publish Test Results” and a “Publish Code Coverage Results” task

npm_publish_test

npm_publish_coverage

Make sure you select “Even if a previous task has failed, unless the build was canceled” on the option “Run this task” under the tab “Control Options” for both publish tasks, as we want tests reports and coverage even if we have failing tests.

In addition you want to set the environment variable CI to true, in order for Jest to run all tests:

ci_true

With these things in place your build should now include test results and coverage reports!