ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Jest] Vite + Typescript + pnpm 환경에서 Jest
    프로그래밍/CSS 2023. 11. 30. 21:36

    개요

    • 설치하기
    • 자주사용하는 Matcher

    1. 설치하기

    Jest 패키지 설치)

    pnpm add -D @types/jest ts-node ts-node ts-jest @testing-library/react identity-obj-proxy jest-environment-jsdom @testing-library/jest-dom jest-svg-transformer

     

    package.json 수정)

    "scripts":{
        ...
        "test": "jest"
     }
    • 실행문구임 이거 추가해줘서 터미널에서 쳐야함

    Jest 설정파일 추가)

    // jest.config.ts
    
    export default {
      testEnvironment: "jsdom",
      transform: {
        "^.+\\.tsx?$": "ts-jest",
      },
      moduleNameMapper: {
        "^.+\\.svg$": "jest-svg-transformer",
        "\\.(css|less|sass|scss)$": "identity-obj-proxy",
      },
      setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
    };
    // jest.setup.ts
    
    import "@testing-library/jest-dom";
    •  

    tsconfig.json 파일 수정

    {
    	"compilerOptions":{
          	...,
    		"esModuleInterop": true      
        }
    }
    • esModuleInterop : Typescript랑 Jest 같이 사용할 때 필요함 (CommonJs 와 ESM간의 상호 운용성 향상을 위함)

    src폴더 아래에 __tests__ 폴더 생성 후 ~~~.test.tsx로 생성 후 테스트 해보기


    Matcher

    toEqual()

    가장 많이 접하게 되는 함수이며 toBe()대신 사용되는 경우가 많다.
    function getUser(id) {
      return {
        id,
        email: `user${id}@test.com`,
      };
    }
    • id를 입력받아서 email을 만드는 컴포넌트가 있다
    test("return a user object", () => {
      expect(getUser(1)).toBe({
        id: 1,
        email: `user1@test.com`,
      });
    });
    • toBe()를 사용할 경우 친절하게 toEqual()을 사용하라고 Jest가 알려준다
     Compared values have no visual difference. Note that you are testing for equality with the stricter `toBe` matcher using `Object.is`. For deep equality only, use `toEqual` instead.

     

     

    toBeTruthy(), toBeFalsy()

    true로 간주되면 통과, false로 간주되면 통과 (단순히 boolean값 뿐만아니라 falsy한 값들 모두 사용 가능)
    test("number 0 is falsy but string 0 is truthy", () => {
      expect(0).toBeFalsy();
      expect("0").toBeTruthy();
    });

     

     

    toHaveLength(), toContain()

    toHaveLength()는 배열의 경우 배열의 길이를 체크할 때 사용되고, toContain()의 경우 특정 원소가 배열에 들어있는지를 확인할 때 사용된다.
    test("array", () => {
      const colors = ["Red", "Yellow", "Blue"];
      expect(colors).toHaveLength(3);
      expect(colors).toContain("Yellow");
      expect(colors).not.toContain("Green");
    });
    • not 이 사용된 것이 보이는데 이건 !랑 똑같은 효과임

     

    toMatch()

    문자열의 경우 단순히 toBe()를 사용해서 일치하는지 체크할 수 있지만 정규식 기반의 테스트가 필요할 때에는 toMatch()를 사용해야 한다
    test("string", () => {
      expect(getUser(1).email).toBe("user1@test.com");
      expect(getUser(2).email).toMatch(/.*test.com$/);
    });

     

     

    toThrow()

    예외 발생 여부를 테스트해야할 때 사용하는 함수
    function getUser(id) {
      if (id <= 0) throw new Error("Invalid ID");
      return {
        id,
        email: `user${id}@test.com`,
      };
    }
    • 음수가 들어왔을 때 에러를 던지도록 할 것임.
    test("throw when id is non negative", () => {
      expect(getUser(-1)).toThrow();
      expect(getUser(-1)).toThrow("Invalid ID");
    });
    • expect() 함수에 넘기는 검증 대상을 함수로 감싸주지 않으면 실패하게 된다.
    test("throw when id is non negative", () => {
      expect(() => getUser(-1)).toThrow();
      expect(() => getUser(-1)).toThrow("Invalid ID");
    });

     

     

     

    참고자료: 블로그1 , 블로그2 , 블로그3 

    댓글

Designed by Tistory.