The Karma test runner is ideal for writing and running unit tests while developing the application. It can be an integral part of the project's development and continuous integration processes.
Next i will describe step by step how to create test in context of out project structure. We have three main file categories - Components, Services, Modules.
Testing Components:
Let's assume we have a components folder with following structure:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent {
title = "Hello world!!!";
}
/app/components/test.component.html
<h1>
{{title}}
</h1>
/app/components/test.component.css
h1 {
color : red;
}
So for create a test you should to do following:
1) Create file test.component.spec.ts in the root of yours components directory. You can create file with any name by "spec.ts" should be always present in it.
2) Add to /app/components/test.component.spec.ts file following content:
import { TestBed, async } from '@angular/core/testing';
import { TestComponent } from './test.component';
describe('AppComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
TestComponent
]
});
TestBed.compileComponents();
});
it('should create the test app', async(() => {
const fixture = TestBed.createComponent(TestComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'Hello world!!!'`, async(() => {
const fixture = TestBed.createComponent(TestComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('Hello world!!!');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Hello world!!!');
}));
});
Testing services and models
Let's assume we have a folder with following structure: