对 toObservable(signal()) 的订阅根本不运行。 Triend 完成,fakeAsync,异步不起作用。
我尝试测试使用信号和可观察量的服务。主要目标是检查 HTTP 调用是否已发送,但我看不到任何内容。在不使用 RxJS 互操作的情况下伪造一个简单的 GET 请求效果很好,但是当我尝试查找由
引起的请求时params = signals({test: 'test'});
result = this.http.get('fake', {
params: new HttpParams({ fromObject: { test: 'test' } }),
});
resultRxjsInterop = toObservable(this.params).pipe(
switchMap(params =>
this.http.get('fake', new HttpParams({ fromObject: params }))
)
);
// Check if the request was sent
const req = httpTestingController.expectOne({
url: 'fake?test=test',
method: 'GET',
});
在订阅结果的情况下,测试通过。但是订阅resultRxjsInterop时,没有发送请求,什么也没有发生,订阅也没有运行。
有人知道如何使用 toObservable 测试服务吗?
此测试将首先订阅
resultRxjsInterop
observable。然后,它将使用 httpTestingController
检查是否发送了预期的 HTTP 请求。如果请求已发送,则测试将通过。否则,测试将失败。
import { TestBed, waitForAsync } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { MyService } from './my.service';
describe('MyService', () => {
let service: MyService;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [MyService],
});
service = TestBed.inject(MyService);
httpTestingController = TestBed.inject(HttpTestingController);
});
it('should send an HTTP request when subscribing to resultRxjsInterop', waitForAsync(() => {
const params = { test: 'test' };
const resultRxjsInterop = service.toObservable(params).pipe(
switchMap(params => service.http.get('fake', new HttpParams({ fromObject: params })))
);
resultRxjsInterop.subscribe();
// Check if the request was sent
const req = httpTestingController.expectOne({
url: 'fake?test=test',
method: 'GET',
});
req.flush({});
expect(req).toBeTruthy();
}));
});