snoopy
snoopy

Reputation: 105

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

    })

Upvotes: 0

Views: 1097

Answers (2)

AliF50
AliF50

Reputation: 18859

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

Upvotes: 1

Roman A.
Roman A.

Reputation: 742

You need to test the result in your .subscribe callback method:

const valToCheck = ...

store
    .pipe(select(studentfilesGetData), takeUntil(this.destroy$))
    .subscribe(studentFiles => expect(valToCheck).toBe(component.getSortedEmployerFiles(studentFiles))

Upvotes: 1

Related Questions