Consider the following functions
const aPrivateAsyncQuery = async () => {
try {
return await axios.post('someURL', {query: 'someQuery'})
} catch (error) {
throw new Error(`A thrown error: ${error}`)
}
}
export const aPublicAsyncFunction = async someVariable => {
const data = await aPrivateAsyncQuery()
if (data[someVariable]){
return data[someVariable]
}
return {}
}
How can one test that aPrivateAsyncQuery
throws an error when aPublicAsyncFunction
is called?
I currently have the following test... which mentions that no throw happened.
it('should throw when nested function throws', async () => {
const someVariable = 'foo'
axios.post.mockRejectedValue(new Error('bar'))
expect(async () => { await aPublicAsyncFunction(someVariable) }).toThrow()
})
Thanks in advance!
EDIT
The following implementation worked perfectly:
it('should throw when nested function throws', async () => {
const someVariable = 'foo'
axios.post.mockRejectedValue(new Error('bar'))
await expect(aPublicAsyncFunction(someVariable)).rejects.toThrowError('bar')
})
It seems that expect toThrow is not very well supported with async functions .
As per that issue, you can test your method with the syntax:
it('should throw when nested function throws', async () => {
const someVariable = 'foo'
jest.spyOn(axios, 'post')
.mockImplementation(() => Promise.reject(new Error('bar')));
await expect(aPublicAsyncFunction(someVariable)).rejects.toThrow(new Error('A thrown error: Error: bar'));
});
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.