jest expect 팁

Falcon·2024년 1월 2일

test

목록 보기
1/2
post-thumbnail

TL;DR;

  • 일반적인 상태/결과 값 검증은 함수 결과를 변수에 할당하여 쓴다.
  • Throw 검증은 arrow function 으로 감싸서 핸들링한다.
  • 비동기 함수는 async/await 을 명시적으로 쓴다.

expect with calling()

정상적인 결과 값을 검증하려할 때

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

expect with no calling

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

사실 권장 사항은 arrow function call 이다.

  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

Async function

신기하게도 동기 함수와 다르게 () 를 써도 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)

profile
I'm still hungry

0개의 댓글