Setting up Unit Tests for our Angular 4 app

Bharat Tiwari
Developing an Angular-4 web app
3 min readJun 13, 2017

- Project Repository: https://github.com/jsified-brains/momentz4ever-web-ng4/
- Branch specific for this task: https://github.com/jsified-brains/momentz4ever-web-ng4/tree/seed-ng4-and-unit-tests

In the previous task, we set up our Angular 4 app from scratch and got it up and running with the first very basic app root component.

Now lets get Karma and Jasmine configured for our unit tests.

  1. Install Karma and Jasmine.
    Open the project folder in command/terminal window and install the tools with the below command:
npm install --save-dev karma jasmine @types/jasmine karma-jasmine
karma-cli

2. Initialize karma configuration using the command karma init and answer the prompted questions:

(click on image to zoom)

The above should create a karma.conf.js file under the project’s root folder.

3. We’ll write unit tests in typescript ( spec.ts ). For typescript to understand jasmine functions, we’ll have to include “jasmine” in types array of tsconfig.json ( line # 21 👇)

4. Next, for karma to work with webpack, we’ll install karma-webpack and karma-sourcemap-loader.

npm install --save-dev karma-webpack karma-sourcemap-loader

5. We’ll write our unit tests in files with extensions spec.ts.
We’ll create a spec.ts file for each of the component or module or any asset we create in our angular application and we’ll store the spec file in the same folder where the component or asset file is located.

Additionally , we’ll have a file named unit-tests.ts created under src folder, which will act as an entry point. In this file we’ll loop through all other spec.ts files inside our src folders/sub-folders and kick off execution of the unit tests in those files.

To start with, under the src folder, lets first create our unit test entry point file unit-tests.ts with a very basic test.

describe('First Unit test', () => {
it('should run as expected', () => {
expect(true).toBeTruthy;
});
});

6. Next, we’ll have to update the karma.conf.js file as below:

i. What files to test:

files: [
{ pattern: './src/unit-tests.ts', watched: false }
],

ii. Pre-process the .ts file with webpack to compile to .js and get its source-map created:

preprocessors: {
'./src/unit-tests.ts': ['webpack', 'sourcemap']
},

iii. At this point, the karma.conf.js file should look something like below:

7. Update the “test” script in package.json as below:

"scripts": {
"test": "karma start",
"build": "webpack-dev-server --config webpack/webpack.config.js"
},

8. Run the tests from command prompt with the command npm run test.

Yay! We got our first unit test passed.

In the next task, we will write few unit tests for our root app component and see how to get those running from our entry test file.

--

--