jest 예시

jest용 치트시트

jest 예시
참고자료
기본
expect(42).toBe(42)
expect(42).not.toBe(3)

//deep검증
expect(any)
  //배열
  .toEqual([1, 2])
  //obj
  .toEqual({b: 2})
  //완전불일치일치
  .not.toStrictEqual({b: 2})
true/false
// 아래중 하나라면 실패
// false,0,'',null,undefined,NaN
expect('foo').toBeTruthy()

// 아래중 하나라면 성공
// false,0,'',null,undefined,NaN
expect('').toBeFalsy()

// null만 성공
expect(null).toBeNull()

// undefined만 성공
expect(undefined).toBeUndefined()

//선언만 되어있음 성공
expect(7).toBeDefined()

// Matches true or false
expect(true).toEqual(expect.any(Boolean));
숫자
//대소비교
expect(number)
  .toBeGreaterThan(1)
  .toBeGreaterThanOrEqual(1)
  .toBeLessThan(2)
  .toBeLessThanOrEqual(1)

//범위
expect(0.2 + 0.1)
  .toBeCloseTo(0.3, 5)

//숫자검증
expect(NaN)
  .toEqual(expect.any(Number));
문자열
expect('long string')
  .toMatch('str')
  .toEqual(expect.any(String))
  //regex
  .toMatch(/ff/)
  .not.toMatch('coffee')


//문자열배열 검증
expect(['pizza', 'coffee'])
  .toEqual([
    expect.stringContaining('zz'),
    expect.stringMatching(/ff/)
  ])
배열
expect([]).toEqual(expect.any(Array))
expect(['Alice', 'Bob', 'Eve']).toHaveLength(3)
expect(['Alice', 'Bob', 'Eve']).toContain('Alice')
expect([{ a: 1 }, { a: 2 }]).toContainEqual({ a: 1 })
expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(['Alice', 'Bob']))
오브젝트
expect({ a: 1 }).toHaveProperty('a')
expect({ a: 1 }).toHaveProperty('a', 1)
expect({ a: { b: 1 } }).toHaveProperty('a.b')
expect({ a: 1, b: 2 }).toMatchObject({ a: 1 })
expect({ a: 1, b: 2 }).toMatchObject({
  a: expect.any(Number),
  b: expect.any(Number),
})
expect([{ a: 1 }, { b: 2 }]).toEqual([
expect.objectContaining({ a: expect.any(Number) }),
expect.anything(),
])
스냅샷
expect(node).toMatchSnapshot()
// Jest 23+
expect(user).toMatchSnapshot({
date: expect.any(Date),
})
expect(user).toMatchInlineSnapshot()
함수 Mock
// const fn = jest.fn()
// const fn = jest.fn().mockName('Unicorn') -- named mock, Jest 22+
expect(fn).toBeCalled() // Function was called
expect(fn).not.toBeCalled() // Function was *not* called
expect(fn).toHaveBeenCalledTimes(1) // Function was called only once
expect(fn).toBeCalledWith(arg1, arg2) // Any of calls was with these arguments
expect(fn).toHaveBeenLastCalledWith(arg1, arg2) // Last call was with these arguments
expect(fn).toHaveBeenNthCalledWith(callNumber, args) // Nth call was with these arguments (Jest 23+)
expect(fn).toHaveReturnedTimes(2) // Function was returned without throwing an error (Jest 23+)
expect(fn).toHaveReturnedWith(value) // Function returned a value (Jest 23+)
expect(fn).toHaveLastReturnedWith(value) // Last function call returned a value (Jest 23+)
expect(fn).toHaveNthReturnedWith(value) // Nth function call returned a value (Jest 23+)
expect(fn.mock.calls).toEqual([
['first', 'call', 'args'],
['second', 'call', 'args'],
]) // Multiple calls
expect(fn.mock.calls[0][0]).toBe(2) // fn.mock.calls[0][0] — the first argument of the first call
기타
expect(new A()).toBeInstanceOf(A)
expect(() => {}).toEqual(expect.any(Function))
expect('pizza').toEqual(expect.anything())
프로미스
test('resolve to lemon', () => {
  return expect(Promise.resolve('lemon')).resolves.toBe('lemon')
  return expect(Promise.reject('octopus')).rejects.toBeDefined()
  return expect(Promise.reject(Error('pizza'))).rejects.toThrow()
})