基于这个问题,我写了这个测试:
it('call service when search product by code', async() => {
let code: string = 'CODE';
let product: Product = createProduct();
let properties: ProductProperties = createProductProperties();
when(mockProductService.getProductByCode(code)).thenReturn(of(product));
when(mockProductService.getProductProperties(product.id)).thenReturn(of(properties));
let result: Product = await sut.searchProductByCode(code);
expect(result.code).toEqual(product.code);
expect(result.properties).toEqual(properties);
verify(mockProductService.getProductByCode(code));
verify(mockProductService.getProductProperties(product.id));
});
我正在测试的功能是:
async searchProductByCode(code: string): Promise<Product> {
let product = await this.productService.getProductByCode(code).toPromise(); //fails running test
product.properties = await this.productService.getProductProperties(product.id).toPromise();
return product;
}
该函数运行正常,但测试失败:
TypeError: this.productService.getProductByCode(...).toPromise 不是函数
就像我没有正确地嘲笑服务一样吗?
productService.getProductByCode() 方法返回 Product 的 Observable:
getProductByCode(code: string): Observable<Product>
(product) 方法创建了一个产品的 Observable 对象。方法 .toPromise() 是 Observable 的一个方法,它从 observable 返回一个承诺。这里是导入:
import { of } from 'rxjs';