【问题标题】:How to unit test Rxjs combineLatest?如何对 Rxjs combineLatest 进行单元测试?
【发布时间】:2020-01-06 12:42:32
【问题描述】:

我的组件的 ngOnInit 这样做

public ngOnInit() {
    this.ctrSubscription = combineLatest(this.route.queryParams, this.tags$).subscribe(async params => {
      if (Object.keys(params[0]).length > 0) {
        this.initView({ ...params[0] });
      }
      if (Object.keys(params[1]).length > 0) {
        this.wsTags = Object.values(params[1]);
      }
      if (params[0] && this.wsTags.length > 0) {
        this.searchWs({ ...params[0] }.q);
        this.pruneData();
      }
    });
  }

这就是我测试它的方式

  it('should perform search and load the results', fakeAsync(() => {
    TestBed.get(ActivatedRoute).queryParams = of({ q: 'test' });
    const initSpy = spyOn<any>(component, 'initView').and.callThrough();
    const subSpy = spyOn<any>(component.tags$, 'subscribe');
    component.wsTags = ensureState(mockTags as any);
    flushMicroTasks();
    fixture.detectChanges();
    flushMicroTasks();
    expect(initSpy).toHaveBeenCalledWith({ q: 'test' });
    expect(subSpy).toHaveBeenCalled();
    expect(component.wsTags).toBe(Object.values(mockTags));
  }));

spys 根本没有被调用。我在运行测试时设置了一个断点以了解该值是否通过,并且我能够捕获正确传递的查询参数,但 if 仍然失败。

我尝试阅读文档以更好地理解堆栈溢出以及此处有关堆栈溢出的各种类似问题,但我无法解决它。我对编写单元测试相当陌生,因此将不胜感激。谢谢。

【问题讨论】:

    标签: angular unit-testing testing rxjs karma-jasmine


    【解决方案1】:

    一个潜在的问题是您在 it 块内模拟 ActivatedRoute。为时已晚,您的ngOnInitcompileComponents 之后的第一个detectChanges 之后运行。

    配置测试模块时,尝试:

    describe('Put description of the test', () => {
      let component: YourComponent;
      let activatedRoute: ActivatedRoute;
      let fixture: ComponentFixture<YourComponent>;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
         declarations: [ YourComponentToTest, 
          // other declarations if need be.
         ],
         providers: [
          provide: ActivatedRoute,
          useValue: {
           queryParams: of({ q: 'test" }),
          }
         ]
       }).compileComponents();
      });
    
      beforeEach(() => {
        fixture = TestBed.createComponent(YourComponentToTest);
        component = fixture.componentInstance;
        activatedRoute = TestBed.get(ActivatedRoute);
        // ngOnInit is ran now -- after the first detectChanges
        fixture.detectChanges();
      });
    
      it('should do what you want', () => {
       // your arrange, act, and assertions.
      });
    })
    

    确保this.tags$ 也已初始化。

    所有这些都是我徒手完成的,所以可能有错别字。

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 1970-01-01
      • 2019-05-01
      • 2017-12-27
      • 2021-02-12
      • 1970-01-01
      • 2019-05-04
      • 2012-01-08
      • 2019-11-02
      相关资源
      最近更新 更多