본문 바로가기
TIL & WIL/오늘의 공부.js

Node.js - TDD 시작하기 (3)

by 김만두_ 2023. 11. 17.

Jest Matcher

Jest는 다른 방법으로 값을 테스트 하도록 matcher 라는 것을 사용한다.

matcher란 '이거 맞아?' 라고 물어보는 메서드리고 보면 된다. 기대한 값이 실제 반환된 값과 일치하는 지를 확인하는 작업을 일컫는다.

 

 

 

  • toEqual()
    • 객체가 일치하는 지 검증
    test('two plus two equal four', () => {
    	expect(2 + 2).toEqual(4)
    }
    
  • toBe()
    • 단순 값 비교
    test('two plus two being four', () => {
    	expect(2 + 2).toBe(4)
    }
    
  • toBeDefined()
    • 변수가 정의 되었는 지 여부를 테스트
  • toBeTruthy() / toBeFalsy()
    • 느슨한 타입 기반 언어인 자바스크립트는 자바같은 강한 타입 기반 언어처럼 true와 false가 boolean 타입에 한정되지 않는다. 따라서 숫자 1이 true, 0이 false로 간주되는 것 같이 모든 타입의 값들을 boolean으로 간주하는 규칙
    • toBeTruthy() : 검증 대상이 true로 간주되면 통과
    • toBeFalsy() : 검증 대상이 false로 간주되면 통과
    test("number 0 is falsy but string 0 is truthy", () => {
      expect(0).toBeFalsy(); // 숫자 0은 false를 의미하기도 하다. true
      expect("0").toBeTruthy(); // 문자열은 true를 의미하기도 하다. true
    });
    
  • toBeCalled() / toHaveBeenCalled()
    • 함수가 호출 되었는 지 여부
    expect().toHaveBeenCalled(); // 함수 호출 O
    expect().not.toHaveBeenCalled(); // 함수 호출 X
    
  • toHaveLength() / toContain()
    • 배열의 경우에는 배열의 길이를 체크하거나 특정 원소가 존재 하는 지 여부를 테스트
    test("array", () => {
      const colors = ["Red", "Yellow", "Blue"];
      
      expect(colors).toHaveLength(3); // 배열길이 3
      expect(colors).toContain("Yellow"); // Yellow 문자열 원소를 가지고 있는지
      expect(colors).not.toContain("Green"); // Green 문자열 원소를 안가지고 있는지
    });
    
  • toMatch()
    • 문자열의 경우 toBe()를 사용해서 체크하지만, 정규식 기반의 테스트를 할 때 사용
    test("string", () => {
      expect(getUser(1).email).toBe("user1@test.com"); // 단순 문자열 비교
      expect(getUser(2).email).toMatch(/.*test.com$/); // 정규식 비교
    });
    
  • toThrow()
    • 예외 발생 여부를 테스트
    • 함수 인자도 받는데, 문자열을 넘기면 예외 메세지를 비교하고 정규식을 넘기면 정규식 체크를 함
    • 주의 할 점은, 반드시 expect() 함수에 넘기는 검증 대상을 함수로 한번 감싸줘야함
    test("throw when id is non negative", () => {
      expect(() => 검증할함수(-1)).toThrow(); // 예외를 검증할때는, 함수를 한번 더 감싸준다.
      expect(() => 검증할함수(-1)).toThrow("Invalid ID");
    });
    
  • toHaveProperty()
    • 객체에 해당 key : value 값이 있는 지 검사
    test("find user property", async () => {
       const user = {
          id : 1,
          name : "Leanne Graham"
       }
       
       expect(user).toHaveProperty("id", 1); // { id : 1 } 이 user 객체에 있느냐? -> true
       expect(user).toHaveProperty("name", "Leanne Graham");
     });
    
  • toBeCalledTimes() / toBeCalledWith()
    • toBeCalledTimes() : 함수가 몇번 호출 되었는 지
    • toBeCalledWith() : 함수가 설정한 인자로 호출 되었는 지
    drink("aa");
    drink("aa");
    
    expect(drink).toHaveBeenCalledTimes(2); // drink함수가 2번 호출?
    expect(drink).toHaveBeenCalledWith("aa"); // drink함수가 "aa" 문자열 인자로 호출?
    
  • toReturn() / toHaveReturned()
    • 함수가 오류없이 반환되는 지
  • toReturnTimes() / toHaveReturnedTimes()
    • 함수가 지정한 횟수만큼 오류없이 반환되는 지
    test('drink returns twice', () => {
      const drink = jest.fn(() => true);
    
      drink();
      drink();
    
      expect(drink).toHaveReturnedTimes(2); // 오류없이 리턴을 무사히 마친 횟수? -> 2
    });
    
  • toReturnWith() / toHaveReturnedWith(value)
    • 함수가 지정한 값을 반환하는 지 테스트
    javascripttest('drink returns La Croix', () => {
      const beverage = {name: 'La Croix'};
      const drink = jest.fn(beverage => beverage.name);
    
      drink(beverage);
    
      expect(drink).toHaveReturnedWith('La Croix'); // drink(beverage) 함수 결과가 'La Croix' 문자열을 반환하는지?
    });