45
loading...
This website collects cookies to deliver better user experience
OnInit
lifecycle when writing the unit tests.Angular CLI
to build our components, we will use ng generate component MyComponent
, and it will generate our component with some boilerplate unit test.import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MyComponent} from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [
MyComponent
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
fixture.detectChanges()
is the method which will trigger OnInit
in our component.@input()
which will tell it the user authorization status.@Component({
selector: 'app-my-component',
template: `
<ng-container *ngIf="isLoggedIn else notLoggedInTemplate">
<app-home></app-home>
</ng-container>
<ng-template #notLoggedInTemplate>
<app-authorization></app-authorization>
</ng-template>
`
})
export class MyComponent implements OnInit {
@Input() isLoggedIn: boolean;
ngOnInit(): void {
if (this.isLoggedIn)
this.doSomethingBaseOnLogIn();
}
}
isLoggedIn
field and then run fixture.detectChanges()
to be able to test if the component behaves as expected.describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [
MyComponent,
AuthorizationComponent,
HomeComponent
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('Behave correctly base on "isLoggedIn" status', () => {
it('should display login component if not logged in', () => {
fixture = TestBed.createComponent(SearchFormComponent);
component = fixture.componentInstance;
component.isLoggedIn = false;
fixture.detectChanges();
const myComponent = fixture.debugElement.nativeElement as HTMLElement;
expect(myComponent.querySelector('app-authorization')).toBeTruthy();
});
it('should display home component if already logged in', () => {
fixture = TestBed.createComponent(SearchFormComponent);
component = fixture.componentInstance;
component.isLoggedIn = true;
fixture.detectChanges();
const myComponent = fixture.debugElement.nativeElement as HTMLElement;
expect(myComponent.querySelector('app-home')).toBeTruthy();
});
});
});
input
by changing the condition every time the component is initialized.