[英]How to write unit test my angular service which uses mergeMap()?
我是 karma/jasmine 框架的新手。
我正在嘗試添加一個測試用例來涵蓋我的服務方法(下)
public getAllChassis(): Observable<Chassis[]> {
return this.http.get('chassis').pipe(
mergeMap((result: Chassis[]) => {
for (const chassis of result) {
chassis.healthStatus = 45;
chassis.complianceStatus = 81;
}
return of(result);
}));
}
這不包括 pipe 語句的回調/內部。 測試這些 mergeMap 模式的正確方法是什么?
我不確定您是否應該使用mergeMap
。 你應該檢查一下。
以下是我如何從發出 HTTP 請求並返回 observable 的服務中測試 function 的方法。
這是我在 Angular 項目中如何使用TestBed
注入依賴項的示例。
let httpClient: HttpClient;
let service: YourService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
...
}).compileComponents();
httpClient = TestBed.get(HttpClient);
service = TestBed.get(YourService);
});
為確保 get 請求返回您想要的內容,您必須對其進行監視並提供虛假結果。
describe("WHEN: getAllChassis", () => {
beforeEach(() => {
const RESPONSE_MOCK = of(
new HttpResponse({
body: {
/* whatever your service returns */
},
})
);
spyOn(httpClient, "get").and.returnValue(RESPONSE_MOCK);
});
// Here will go your test
});
要測試您的功能,請檢查它是否返回您所期望的(考慮到我們知道 http.get 將返回什么)。
請注意,我使用的done
,因為這是一個異步 function。 在調用完成(或超時)之前,測試不會結束。
it("THEN: should return data", (done) => {
getAllChassis()
.pipe(take(1))
.subscribe((data) => {
expect(data).toEqual({
/* what you expect in result */
});
done();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.