测试返回可观察操作符的函数的最佳方法

huangapple go评论54阅读模式
英文:

Best way to test a function that returns an observable operator

问题

测试返回具有 tap 操作符的 observable 的最佳方法。

operations(numbers): Observable{
const sumValue = numbers[0]+numbers[1]
return sumService.getOperations(sumValue).pipe(tap(randomOperationValue => {this.value = randomOperationValue}
))
}


我不知道如何测试 tap 内部的值。我尝试模拟 getOperations(),但没有成功。
英文:

Best way to test a function that returns an observable with tap operator.

operations(numbers): Observable{
  const sumValue = numbers[0]+numbers[1]
  return sumService.getOperations(sumValue).pipe(tap(randomOperationValue => {this.value =    randomOperationValue}
))
}

I do not see how to test the value inside tap. I tried to mock getOperations() but without success.

答案1

得分: 0

描述('AppComponent', () => {
let svc: OperationsService;
let fixture: ComponentFixture;
let component: AppComponent;

在每个测试前(async () => {
TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [{
provide: OperationsService,
useValue: {
getOperations: () => of(1000),
}
}]
});

svc = TestBed.inject(OperationsService);
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;

});

it('应该……', fakeAsync(() => {
const spy = jest.spyOn(svc, 'getOperations');
const obs$ = component.operations([100, 200]);

obs$.subscribe();
tick();

expect(spy).toHaveBeenCalledWith(300);
expect(component.value).toBe(1000); // 这是我们模拟的固定值 ^

}));
});

英文:

A quick something should get you started

describe('AppComponent', () => {
  let svc: OperationsService;
  let fixture: ComponentFixture<AppComponent>;
  let component: AppComponent;

  beforeEach(async () => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [{
        provide: OperationsService,
        useValue: {
          getOperations: () => of(1000),
        }
      }]
    });

    svc = TestBed.inject(OperationsService);
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
  });

  it('should ...', fakeAsync(() => {
    const spy = jest.spyOn(svc, 'getOperations');
    const obs$ = component.operations([100, 200]);

    obs$.subscribe();
    tick();

    expect(spy).toHaveBeenCalledWith(300);
    expect(component.value).toBe(1000); // this is the fixed value we mock ^
  }));
});

huangapple
  • 本文由 发表于 2023年4月11日 05:25:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75980861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定