简体   繁体   中英

How to check return value in Jest

I'm doing unit testing with jest and was able to successfully run some of it but there's certain code that I don't know how to test.

I have Create Organization method that needs to check first if the organization is already exist.

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)
}

and so far this is the unit test code that I was able to cover

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)
    })
})

now what I want to test is this part

const organizationExist = await this.OrganizationRepository.getOne({name: opt.name})
if (organizationExist) {
    throw new Error('Organization already exist')
}

I want to throw an error if the organization is already exist using the name parameter.

Hope you guys can help me. Thanks

you could use toThrowError to test this scenario.

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"));
});

你在找toThrow()吗?

expect(() => someFunctionCall()).toThrow();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM