我正在使用 jest 进行单元测试,并且能够成功运行其中的一些代码,但有些代码我不知道如何测试。
我有创建组织方法,需要首先检查组织是否已经存在。
async createOrganization(opt) {
try {
const organizationExist = await this.OrganizationRepository.getOne({name: opt.name})
if (organizationExist) {
throw new Error('Organization already exist')
}
} catch (error) {
throw error
}
let organizationObject = {}
organizationObject.name = opt.name
return this.OrganizationRepository.save(organizationObject)
}
到目前为止,这是我能够涵盖的单元测试代码
describe('Create Organization', () => {
it('should call getOne function', () => {
const mockGetOne = jest.spyOn(OrganizationRepository.prototype, 'getOne')
organizationService.createOrganization(expectedOrganization)
expect(mockGetOne).toHaveBeenCalledWith({name: 'sample org'})
})
it('should return created organization', async () => {
const mockSave = jest.spyOn(OrganizationRepository.prototype, 'save')
mockSave.mockReturnValue(Promise.resolve(expectedOrganization))
const result = await organizationService.createOrganization({name: 'sample org'})
expect(mockSave).toHaveBeenCalledWith({name: 'sample org'})
expect(result).toBe(expectedOrganization)
})
})
现在我要测试的是这部分
const organizationExist = await this.OrganizationRepository.getOne({name: opt.name})
if (organizationExist) {
throw new Error('Organization already exist')
}
如果使用名称参数的组织已存在,我想抛出错误。
希望大家能帮帮我。谢谢
最佳答案
您可以使用toThrowError
来测试此场景。
it("Should throw error", async () => {
const mockGetOne = jest.spyOn(OrganizationRepository.prototype, 'getOne')
await organizationService.createOrganization({ name: 'sample org' }); ;
expect(mockGetOne).toHaveBeenCalledWith({ name: 'sample org' });
// Test the exact error message
expect( organizationService.createOrganization({ name: 'sample org' }))
.resolves
.toThrowError(new Error("Organization already exist"));
});
关于javascript - 如何在 Jest 中检查返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60843620/