virtualninja
virtualninja

Reputation: 192

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

Upvotes: 2

Views: 2696

Answers (2)

Sohail Ashraf
Sohail Ashraf

Reputation: 10569

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

Upvotes: 2

ray
ray

Reputation: 27245

Are you looking for toThrow()?

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

Upvotes: 0

Related Questions