정상적인 결과 값을 검증하려할 때
describe('Jest expect test', ()=>{
// ❌ Error occurs
// Error: expect(received).toBeFalsy()
// Received: [Function getFalse]
test('jest call function in expect clause', ()=>{
const getFalse = () => false
expect(getFalse).toBeFalsy()
})
// ✅
test('Could not assert value before function call being passed to expect', ()=>{
const getFalse = () => false
expect(getFalse()).toBeFalsy()
})
}
Exception 에러를 검증하려 할 때는 () 을 생략하면
jest 가 내부적으로 expect() 문 내에서 함수를 호출한다.
// ❌ Error occurs
test('Could not catch error called before function call being passed to expect', ()=>{
const getError = () => { throw new Error('error thrower') }
expect(getError()).
toThrow('error thrower')
})
test('Able to catch called by jest', ()=>{
const getError = () => { throw new Error('error thrower') }
// ✅
expect(getError).
toThrow('error thrower')
})
test('Able to catch called in arrow function', ()=>{
const getError = () => { throw new Error('error thrower') }
expect(()=>getError()).
toThrow('error thrower')
})
TIP
You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail. - jest docs
신기하게도 동기 함수와 다르게 () 를 써도 rejects 에서 잡히고, () (parenthesis) 을 생략해도 잘 잡힌다.
// ✅
test('Async function Internal calling resolves by jest', async ()=>{
const getFalse = async (): Promise<boolean> => false
await expect(getFalse()).resolves.toBeFalsy()
})
// ✅
test('Async function Internal calling rejected by jest with await with arrow function', async ()=>{
const getAsyncError = async (): Promise<boolean> => { throw new Error('error thrower') }
await expect(getAsyncError()).rejects.toThrow('error thrower')
})
//✅
test('Async function Internal calling rejected by jest', ()=>{
const getAsyncError = async (): Promise<boolean> => { throw new Error('error thrower') }
expect(getAsyncError).rejects.toThrow('error thrower')
})
//✅
test('Async function Internal calling rejected by explicit call', async ()=>{
const getAsyncError = async (): Promise<boolean> => { throw new Error('error thrower') }
expect(getAsyncError()).rejects.toThrow('error thrower')
})
결과를 변수에 담아서 검증하라.
Arrow function ()=> 으로 감싸서 검증하라.
(feat. rejects, await)