【问题标题】:How to unit test the store onInit using jest and angular如何使用 jest 和 angular 对商店 onInit 进行单元测试
【发布时间】:2021-05-26 23:15:47
【问题描述】:

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

    })

【问题讨论】:

    标签: angular jestjs sonarqube


    【解决方案1】:

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

    尝试显式调用它:

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2020-01-29
        • 2020-07-26
        • 1970-01-01
        • 2021-08-08
        • 1970-01-01
        • 2020-12-30
        • 2020-11-12
        • 2020-12-28
        • 1970-01-01
        相关资源
        最近更新 更多