如何在Karma中对fork进行单元测试

问题描述 投票:0回答:1

我有一个使用forkJoin的代码,它是这种方式,

forkJoin(serviceRequests).subscribe((forkResults) => {
                //Do stuff with forkResults here 
});

我如何模拟订阅,以便还可以评估其中的代码。

我尝试了以下类似的各种操作

spyOn(Observable, 'forkJoin').and.returnValue(of(mockedResults));
angular rxjs observable karma-jasmine
1个回答
0
投票

//首先,我假设您在像]这样的函数中使用forkJoin

  func() {
    forkJoin(this.getForkedStreams()).pipe(takeUntil(this.unsubscribe)).subscribe((streams: any[]) => {
      console.log(streams[0]);
      console.log(streams[1]);
      console.log(streams[2]);

      // logs the array objects provided by the streams
    });
  }
  getForkedStreams() {
    return [
      this.service.func1(),
      this.service.func2(),
      this.service.func3()
    ];
  }

//然后在spec文件中将流数组模拟为

//模拟如下服务功能:

     let mockService: any;
    mockService = {
  func1: () => {
    return of({
      prop: 'xyz'
    });
  },
  func2: () => {
    return of({
      prop: 'xyz'
    });
  },
  func3: () => {
    return of({
      prop: 'xyz'
    });
  }
};

//服务注入新的SampleComponent(mockService任意);

   /*
Then, in the actual describe => it block, assert against the values mocked up with the variable with which it would be assigned to.
I am not doing that since it is only the mocking that you've asked and you might want to continue from there
*/
© www.soinside.com 2019 - 2024. All rights reserved.