Premier Developer consultant Wael Kdouh brings us this post on integrating Angular 4 unit tests into VSTS.
One of the nice features of Angular 4 (and Angular 2 before it) is the introduction of the Angular CLI (command line interface). I like to think of it as a style guide coming straight from the Angular team. But more importantly, it takes care of all the ceremony that accompanies building an Angular application like setting up module bundlers with WebPack, setting up unit testing with Jasmine, setting up end to end testing with protractor, etc.
Angular CLI was used to scaffold the project. It leverages Jasmine to define the unit tests and Karma as the test-running framework. There are two challenges to running these tests on the build server:
- The tests depend on browsers that aren’t available on the build server
- The generated output of the test results is not included in the final build report
Getting Rid of The Browser Dependency
npm i phantomjs-prebuilt --save-dev
As mentioned before the Angular CLI uses Karma to run the unit tests. Karma uses special packages to link to the browsers called launchers. Here you will need to install the PhantomJS launcher using the following command:
npm i karma-phantomjs-launcher --save-dev
Add the PhantomJS launcher to the list of plugins under the Karma.config.js file
Also modify the browsers property to launch PhantomJS as follows:
Generate Test Results To Be Included In The Build Report
npm i karma-junit-reporter --save-dev
This can be added to the Karma config file the same way the PhantomJS launcher was:
In addition, make sure that Junit is also added to the array of reporters:
You will also need to setup the Junit reporter as follows:
It’s Time To Setup The Build Server
Start by creating an empty build:
Once the new build definition is created add the following build steps:
The first build step installs the Angular CLI on the build server. The package manager command is install and the arguments are:
The second step ensures that the dependencies of the project are installed. This is achieved by using the install command with no arguments:
With the Angular CLI installed the build step is now ready to run the tests and generate the output file. Here we set the reporters flag to run both the progress as well as Junit in order to both see the test results on the command line on the build server and write to the output file which will be parsed in the last build step:
The last step instructs VSTS to read the file generated in the previous step and include it in the build report:
Looking at the setup above the assumption is that the reporter was setup under the Karma configuration file to write to a file called test.xml.