我有一个使用模拟的测试类。该模拟在 2 个类 ProductSearch 和 ProductUpdate 中定义,它们具有精确的模拟 ProductRepository 模拟定义。这是包含模拟的类
export class ProductRepository {
public async findProductByCategory(){
return await ProductCategoryModel.find({})
}
}
```
export class ProductSearch {
productRepository:ProductRepository
constructor(){
this.productRepository = new ProductRepository()
}
public async findAllProductsByCategory(){
return await this.productRepository.findProductByCategory()
}
}
export class ProductUpdate {
productRepository:ProductRepository
constructor(){
this.productRepository = new ProductRepository()
}
public async updateProductsByCategory(category: string ){
const product = await
this.productRepository.findProductByCategory()
//update category of product
}
}
// 我在两个类中以同样的方式定义模拟
const findProductByCategoryMock = jest.fn()
jest.mock('../../repository/product-repository', () => {
return {
ProductRepository: jest.fn().mockImplementation(() =>
{
return {
findProductByCategory: findProductByCategoryMock,
}
})
}
})
it('should find and update product given category',async()={
const mockedProduct = ....
findProductByCategoryMock.mockResolvedValueOnce(mockedProduct)
//.... rest of the test
}
}
不幸的是,Jest 在我调用它时抱怨以下错误 updateProductsByCategory 方法中的 ProductUpdate
TypeError: this.productRepository.findProductByCategory is not a function
我解决了。我在 beforeEach() 生命周期方法中使用 jest.resetAllMocks() 。在导致问题之前我还在初始化测试类实例