Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unit testing for ngAfterViewInit?

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);
    }
}
like image 204
Ramesh vemula Avatar asked Mar 21 '19 06:03

Ramesh vemula


1 Answers

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

like image 192
Massimiliano Sartoretto Avatar answered Sep 29 '22 06:09

Massimiliano Sartoretto