문미새 개발일지

Jest expect() 본문

개발 TIL

Jest expect()

문미새 2025. 4. 24. 18:50
728x90

expect()는 jest에서 사용하는 테스트 대상 값의 기대 조건을 지정할 때 사용하는 함수이며 검사 방식에 따라 사용하는 메소드가 다르다.

 

기본 비교

Matcher 설명 예시
toBe(value) 정확히 같은 값을 기대 (===) expect(1 + 2).toBe(3)
toEqual(value) 객체/배열 등 구조까지 같음을 기대 expect({ a: 1 }).toEqual({ a: 1 })
toStrictEqual(value) toEqual보다 더 엄격 (undefined 등도 체크) expect([1, undefined]).toStrictEqual([1, undefined])
toHaveTextContent(value) 같은 텍스트 값을 기대 expect("moon").toHaveTextContent("moon")
not.@@() 값이 다름을  기대 expect(1).not.toBe(2)

Boolean 검사

Matcher 설명 예시
toBeTruthy() true처럼 평가되는 값 기대 expect("hello").toBeTruthy()
toBeFalsy() false처럼 평가되는 값 기대 expect(0).toBeFalsy()
toBeNull() null인지 검사 expect(null).toBeNull()
toBeUndefined() undefined인지 검사 expect(undefined).toBeUndefined()
toBeDefined() 정의되어 있는지 검사 expect('hi').toBeDefined()

 


Number 검사

Matcher 설명 예시
toBeGreaterThan(number) 초과 expect(10).toBeGreaterThan(5)
toBeLessThan(number) 미만 expect(3).toBeLessThan(10)
toBeGreaterThanOrEqual(number) 이상 expect(5).toBeGreaterThanOrEqual(5)
toBeCloseTo(number[, precision]) 부동소수점 근사 비교 expect(0.1 + 0.2).toBeCloseTo(0.3, 5)

 


그 외 검사

Matcher 설명 예시
toMatch(regex or string) 정규식이나 문자열 포함 여부 검사 expect('Hello World').toMatch(/World/)
toContain(item) 배열 안에 포함되는 값 검사 expect([1, 2, 3]).toContain(2)
toHaveLength(number) 길이 검사 expect([1, 2, 3]).toHaveLength(3)
toHaveProperty(keyPath[, value]) 객체에 속성이 있는지 검사 expect(obj).toHaveProperty("user.name", "철수")
toThrow() 에러 발생을 기대 expect(() => throwError()).toThrow()
toThrowError("에러메시지") 특정 메시지 포함된 에러 발생 expect(() => throwError()).toThrow("오류")

 

예시)

  // 경험치가 100을 넘었을 때
  it("경험치가 100을 넘었을 때, 레벨업하고 나머지가 처리되야 한다.", () => {
    const { getByTestId, getAllByTestId } = render(
      <ExpBox level={21} maxExp={maxExp} currentExp={105} />
    );

    expect(getByTestId("exp-level")).toHaveTextContent("LV.22");

    const filledBlocks = getAllByTestId("filled-block");
    expect(filledBlocks.length).toBe(1);
  });

toHaveTextContent를 사용하여 레벨업이 올바르게 완료되었는지, 그리고 레벨업하고 남은 경험치만큼 경험치 바가 채워지는지 테스팅하는 코드이다.

 

  // 경험치 값이 올바르게 출력되는지
  it("경험치 값이 올바르게 출력된다.", () => {
    const { getByText } = render(
      <ExpBox level={21} maxExp={maxExp} currentExp={30} />
    );

    expect(getByText("(30 / 100XP)")).toBeTruthy();
  });

toBeTruthy를 사용하여 현재 가지고 있는 경험치대로 수치가 정확히 나오는지 테스팅하는 코드이다.

 

테스팅 학습을 위해 몇 가지 기능을 사용해보니, "꼭 이 상황엔 이 테스팅 코드를 사용해야 한다." 같은 건 없는 것 같다.

텍스트 값이 존재하는걸 boolean뿐 만 아니라 텍스트 비교로도 테스팅할 수 있고, 해당 id를 가진 태그가 존재하는지 확인하는 것도 다양한 기능으로 테스팅이 가능하여 자유롭게 손에 익은 기능으로 쓰면 될 것 같다.

728x90

'개발 TIL' 카테고리의 다른 글

react-native expo에서 jest testing  (0) 2025.04.23
LinearGradient  (0) 2025.04.23
앱플레이어 expo 연동, 구글 로그인 구현 중  (0) 2025.04.02
React-Native Expo에 Tailwind 적용하기  (0) 2025.03.31
개발 회고  (0) 2025.03.26