英文:
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 ^
}));
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论