首页 > 解决方案 > 如何对返回 http.patch 响应的 observable 进行单元测试?

问题描述

我是 Angular 8 单元测试的新手。我想测试一个可观察的函数,该函数在服务类中返回 http.patch 响应:

updateStatus(id: string, status: string): Observable<any> {
    if (id === undefined || id === null || status === undefined || status === null) {
        throw new Error('Cannot validate');
    }
    if (environment.role !== 'manager') {
        return this.http.patch<string>(`${environment.ApiUrl}${id}/${status}`, {});
    } else {
        return this.http.patch<string>(`${environment.ApiUrl}${id}/${status}`, this.httpOptions);
    }
}

调用 observable 的函数是:

update(pt: IPointView, status: string) {
    this.isLoading = true;
    this.pointsService.updateStatus(pt.id.toString(), status).subscribe(
    value => {
        this.context.info(pt.id, `Update the status to ${status}`, pt);
        this.isLoading = false;
        
        if (pt.ptType === this.ptTypeRode ) {
            this.open(pt);
    }
    },
    error => {
        this.context.error(pt.id, `Error to update the status to ${status}`, pt);
        this.isLoading = false;
    }
    );
}

我如何测试这个更新方法?我想覆盖这个函数内部的漏洞代码。

标签: angularjasminekarma-jasmine

解决方案


我的建议是模拟该服务,因此在调用“更新”之前,您可以执行以下操作:

spyOn(yourService, 'updateStatus').and.returnValue(of("yourString"));

除了您真正控制服务器可以返回的内容之外,还有利于您的测试。

(此行必须在测试本身中,在实际调用您的“更新”状态之前......从不在生产代码中)


推荐阅读