如何使用 jest 和 angular 对商店 onInit 进行单元测试

How to unit test the store onInit using jest and angular

How to unit test the store using jest and angular,sonarqude 不包括这一行。感谢您的回复

在我的component.ts

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

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

    })

您需要在 .subscribe 回调方法中测试结果:

const valToCheck = ...

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

也许 ngOnInit 没有被 运行 在你的测试中。

尝试显式调用它:

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