首页 > 解决方案 > 如何使用 jest 和 angular 对商店 onInit 进行单元测试

问题描述

如何使用 jest 和 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();
    });

    })

标签: angularjestjssonarqube

解决方案


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

const valToCheck = ...

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

推荐阅读