I am new to writing unit test cases for angular. I have to write a test case for ngAfterViewInit. I don't know how to start. I am using angular 7.
My component code:
export class MyAccessComponent implements OnInit, AfterViewInit {
    // Spinner
    pageLoaded: boolean;
    @Input() diameter = 64;
    @Input() strokeWidth = 7;
    // Icons
    faEdit = faEdit;
    dataSource;
    @ViewChild(MatPaginator) paginator: MatPaginator;
    constructor(private router: Router, private userService: UserService) { }
    ngOnInit() {
        this.pageLoaded = false;
        // Data table init
        this.getUsers();
    }
    ngAfterViewInit() {
        setTimeout(() => {
            this.pageLoaded = true;
        }, 500);
    }
}
                You can invoke lifecycle hooks programmatically using the component instance, like:
beforeEach(() => {
  fixture = TestBed.createComponent(MyAccessComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});
it('should set pageLoaded after view init', () => {
  component.ngAfterViewInit();
  expect(component.pageLoaded).toBe(true);
});
Keep in mind that since you are using a timeout in the hook, you'll need to use fakeAsync to test properly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With