我有服務。
export const PostService = jest.fn().mockReturnValue({
findPost: jest.fn().mockResolvedValue(false),
updatePosts: jest.fn().mockResolvedValue(false),
});
我將服務匯入我的(nestjs)測驗模塊并模擬它。
import { PostService } from '../post.service';
jest.mock('../post.service')
const module: TestingModule = await Test.createTestingModule({
controllers: [PostController],
providers: [PostService]
}).compile();
postService = module.get<PostService>(PostService);
我想更改模擬 postService 中函式的實作以進行不同的測驗。
test('findPost should return false', () => {
postController.getPost() // This calls postService.findPost(), which returns false
})
test('findPost should return true', () => {
// I'm trying to change the implementation here, and then calling the controller
postService.findPost.mockImplementation(() => true) // Error: mockImplementation is not a function
postController.getPost() // This should call postService.findPost() and return true
})
如何根據測驗用例更改模擬服務中任何功能的實作?例如,如果我想測驗一個根據引數拋出錯誤的服務方法。
已經測驗了兩周,閱讀了 jest 檔案,嘗試了 jest.doMock,弄亂了工廠引數,并在每個測驗中匯入服務并在每個測驗用例中模擬它。我能找到的關于每個測驗用例更改 mockImplementation 的所有示例都是針對單個模擬函式,而不是回傳包含多個函式的物件的玩笑函式。
uj5u.com熱心網友回復:
我通常是這樣做的
const serviceMock = jest.fn(() => ({
methodMock(): () => { ... }
})
然后,在 beforeEach 函式中添加這個服務作為提供者
const module: TestingModule = await Test.createTestingModule({
controllers: [MyController],
providers: [
{
provide: MyService,
useValue: serviceMock,
},
],
}).compile();
controller = module.get<MyController>(MyController);
如果我只想對某些測驗用例執行此操作,我只需將此代碼添加到測驗用例。如果我需要在一堆測驗用例中使用它,我將它包裝在一個函式中
uj5u.com熱心網友回復:
事實證明,解決方案很簡單,我只需要:
jest.spyOn("service, "method").mockImplementation(() => { implementation... })
這可以改變任何測驗用例中任何模擬函式的實作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/455839.html
