Angular is a popular open-source JavaScript framework used for building web applications. Testing is an important aspect of software development, and Angular provides several tools and frameworks for testing. In this tutorial, we will discuss how to set up Jasmine and Karma for unit testing in Angular.
Prerequisites
Before we begin, make sure you have the following installed on your system:
- Node.js (version 10 or higher)
- Angular CLI (version 8 or higher)
Setting up Jasmine and Karma
Jasmine is a popular testing framework for JavaScript, and Karma is a test runner that allows you to run tests in a browser environment. Here’s how to set up Jasmine and Karma for unit testing in Angular:
- Install Jasmine and Karma:
npm install --save-dev jasmine karma karma-jasmine karma-chrome-launcher
- Initialize Karma:
ng config cli.defaultCollection @angular/cling generate karma-config
- Update the
karma.conf.js
file:
Replace the contents of the karma.conf.js
file with the following:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/angular-testing'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
- Update the
angular.json
file:
Add the following code to the test
section of the angular.json
file:
"options": {
"karmaConfig": "./karma.conf.js"
}
Writing Unit Tests with Jasmine
Now that we have set up Jasmine and Karma, let’s write a simple unit test for an Angular component.
- Create a new component:
ng generate component my-component
- Open the
my-component.component.ts
file and add the following code:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
<div>
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</div>
`
})
export class MyComponentComponent implements OnInit {
title = 'My Component';
message = 'Hello, world!';
constructor() {}
ngOnInit() {}
}
- Create a new file called
my-component.component.spec.ts
in the same directory and add the following code:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponentComponent } from './my-component.component';
describe('MyComponentComponent', () => {
let component: MyComponentComponent;
let fixture: ComponentFixture<MyComponentComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [MyComponentComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should display the title', () => {
const title = fixture.nativeElement.querySelector('h1');
expect(title.textContent).toContain(component.title);
});
it('should display the message', () => {
const message = fixture.nativeElement.querySelector('p');
expect(message.textContent).toContain(component.message);
});
});
- Run the tests:
ng test
If everything is set up correctly, you should see the tests pass in the terminal.
Conclusion
In this tutorial, we discussed how to set up Jasmine and Karma for unit testing in Angular and wrote a simple unit test for an Angular component. Unit testing is an important aspect of software development, and Angular provides several tools and frameworks for testing. By following this tutorial, you can get started with unit testing in Angular and ensure that your code is robust and maintainable.