我已經為我的Nest.js專案寫了一個單元測驗。我只想確認這個測驗是否正確?
我對單元測驗非常陌生。請花點時間看一下這個。如果這是個奇怪的問題,我真的很抱歉。
我正在測驗nest服務檔案。以下是代碼:
tasks.service.tsasync getTaskById(id: string)。Promise<Task> {
const found = await this.taskModel.findById(id) 。
if (! found) {
throw new NotFoundException(`Task not found`) 。
}
return找到。
}
tasks.service.spec.ts
const mockTask=(/span>)=> {
return {
_id: '613e4135ea46be481c2d88b2',
name: 'Task 1',
description: 'Go to school'。
};
};
const tasksServiceMock: Partial<TasksService> = {
getTaskById: jest.fn().mockResolvedValue(mockTask() )。)
};
describe('TasksService', () => {
let service: TasksService。
beforeEach(async ( ) => {
const module: TestingModule = await Test.createTestingModule({
providers: [
TasksService,
{
provide: TasksService,
useValue: tasksServiceMock,
},
],
}).compile()。
service = module.get<TasksService>(TasksService)。
});
it('should be defined', () => {
expect(服務).toBeDefined()。
});
describe('getTaskById', () => {
it('should get task by ID', async ( ) => {
const task = await service.getTaskById(mockTask()._id) 。
expect(task).toEqual(mockTask())。
});
it('should throw task Not found error', async ( ) => {
tasksServiceMock.getTaskById = jest
.fn()
.mockRejectedValue(new NotFoundException('Task not found'/span>))。
expect.assertions(2)。
try {
await service.getTaskById('123456')。
} catch (e) {
expect(e).toBeInstanceOf(NotFoundException)。
expect(e.message).toBe('Task not found'/span>)。
}
});
});
});
如果你進一步需要任何代碼或細節,請告訴我。 期待您的回答。謝謝你。
uj5u.com熱心網友回復:
你正在正確地覆寫單元測驗。 我有2個關于語法的建議:
mockTask定義為一個物件,而不是指定箭頭函式try catchit("should throw task Not found error"/span>, async () => {
const mockError = new NotFoundException("沒有找到任務")。
tasksServiceMock.getTaskById = jest.fn().mockRejectedValue(mockError)。
expect.assertions(2)。
await expect(service.getTaskById("123456") )。 rejects.toThrowError(mockError)。
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/307916.html
標籤:
上一篇:攝像機影像的位圖訪問違規例外
