Search code examples
angularjestjssonarqube

How to unit test the store onInit using jest and angular


How to unit test the store the following using jest and angular, sonarqude is not covering this line. Thank you for response

In my component.ts

public ngOnInit(): void {
 this.store
      .select(studentfilesGetData)
      .pipe(takeUntil(this.destroy$))
      .subscribe(studentFiles => {
        this.studentFiles = this.getSortedEmployerFiles(studentFiles );
      });
}

In my component.spec.ts

 beforeEach(() => {
    store = mock(Store);
      component = new myComponent(instance(store));
    when(store.select(studentfilesGetData)).thenReturn(of(studentFiles));
  });

  describe('ngOnInit', () => {
    test('should create', () => {
      expect(component).toBeTruthy();
    });

    })

Solution

  • Maybe ngOnInit is not being ran in your test.

    Try explicitly calling it:

    test('should set studentFiles', () => {
      component.ngOnInit();
      expect(component.studentFiles).toBeTruthy(); // can do your own assertions
    });