'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);
    }
}


Solution 1:[1]

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

Solution 2:[2]

Consider using the new approach to testing:

describe('MyComponent', () => {

  let component: MyComponent;

  beforeEach(() => {
    component = new MyComponent(mockMyService());
  });

  describe('ngAfterViewInit', () => {
    it('should do stuff', () => {
      component.ngAfterViewInit();
      expect(component.something.toEqual('something');
    });
  });

});

This is much cleaner and faster-to-test than having to invoke the TestBed

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Massimiliano Sartoretto
Solution 2 Boris Yakubchik