How to test your Angular app
Tests are very important for your code stability, they should follow guidelines and well tested best practices not so easy to remeber. When I surf the net, looking for answers, not everything is suitable for my needs. So that's why I need to list down all the small things that I'm learning day by day.
Test file location
If you are using the Angular CLI or the Nx Console, you are exploiting the Jasmine test framework. So the test file will always be in the component folder, with the extension .spec.ts
.
I got to use the Nx Console, a VSCode extension, and I find it very handy to generate the scheleton of a component with all I need.
How to write a test
The generated test file is initialized with the scheleton:
import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import { TestComponent } from "./test.component";
describe("TestComponent", () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [TestComponent]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it("should create", () => {
expect(component).toBeTruthy();
});
});
Since in my code every component corresponds to a module, instead of declaring the component, I import the module. In this example the first beforeEach
would become:
beforeEach(async(() => {
TestBed.configureTestingModule({
import: [TestComponentModule]
}).compileComponents();
}));
Created the test, I declare all the variables at the beginning of the describe
block and, if they will be used in more then one test and I usually instantiate them in the beforeEach
block, before the instruction fixture.detectChanges()
.
TestBed.createComponent()
creates an instance of the TestComponent, adds a corresponding element to the test-runner DOM, and returns a ComponentFixture.
The fixture created contains all you need to test a component. In particular it containes a DebugElement
, useful to test assertion and inspect the component, and a nativeElement
that contains the actuial HTML. Usually is needed the DebugElement
.
The fixture method detectChanges()
trigger a change detection cycle for the component. This method is usually called in the beforeEach
, after applying some changes to the component, or in the single test after applying the changes to the component.
A good practice should be to group the input variables under different test suites and apply the changes in the beforeEach
body, instead of in the single test body.