개발 노트

jest 본문

카테고리 없음

jest

Meter216 2023. 4. 24. 17:50

Jest 

jest는 프레임워크긴 하지만 실행기다
< jest도 config파일이 원래 존재한다 default 값이 "filename.test.확장자" 를 모두 찾아서 실행시킨다.>
jest node를 통해 전부 다 실행시킴 (jest > 파일 목록을 보고 node를 붙여 실행시켜준다.)

jest 는 단순히 프레임워크 테스트 코드를 관리해주는 라이브러리

jest는 기본적으로 javascript 에서 실행되는것이다. ts에서 실행시키기 위해선 따로 설정이 필요하다.

TDD

기본 설정

npm install -D jest @types/jest ts-jest

npm jest를 통해서 실행 >> jest 내부에 가진 모듈을 가져와서 실행을 시킨다. 

 

@type > interface등을 모아놓은 라이브러리이다

 

npx jest --preset ts-jest


실행을 시키는데 ts-jest 로 실행을 시킨다는 것  >>>  typescript 환경으로 실행하는 jest 가 실행되도록

 

--testEnvironment node을 추가한다.

    "jest": {
        "preset": "ts-jest",
        "testEnvironment": "node",
        "globals": {
            "transform": {
                ".ts": "ts-jest"
            },
            "ts-jest": {
                "tsconfig": "tsconfig.json"
            }
        }
    }

jestconfig.jso 파일을 이렇게 작성해준다면 jest 를 ts환경에서 실행시킬 수 있게 된다.

이를 package.json 에 합쳐도 작동한다.

 

 

TDD는 기본적으로 테스트 코드 먼저 작성해야한다

 

1. test 코드 작성 

describe("Comment Service", () => {})

 

뭘 테스트 할 지  ??  "Comment Service"

빈 클래스 작성

class BoardService{

}

export default BoardService


path 작성

이후 인스턴스 생성, 메서드 확인

describe("Comment Service", () => {
    let commentService: CommentServicer;
    beforeEach(() => {
        commentService = new CommentServicer(commentRepository);
    });

    it("commentService 인스턴스 확인하기", () => {
        expect(typeof commentService).toBe("object"); //단순 객체가 맞는지 확인
        expect(commentService instanceof CommentServicer).toBeTruthy(); //더 확실한 방법, type이 commentService가 맞는지 확인 
    });
    describe("Comment 글쓰기", () => {
        it("commentwrite", () => {
            expect(typeof commentService.write).toBe("function"); // 함수가 맞는지 확인
        });
    });
});

 

이후 , 인자값을 받고 있는지, 리턴값이 맞는지를 체크

 

import { CommentWriteDTO } from "@comment/comment.interface";
import CommentServicer from "@comment/comment.service";
import CommentRepository from "@comment/comment.repository";

describe("Comment Service", () => {
    let commentService: CommentServicer;
    let commentRepository: CommentRepository;
    beforeEach(() => {
        commentRepository = {
            create: jest.fn().mockResolvedValue({ id: 0, writer: "cheol", comment: "asfsafaf", boardid: 0 }), //리턴 값 체크를 위한 가상의 함수 
        };
        commentService = new CommentServicer(commentRepository);
    });

    it("commentService 인스턴스 확인하기", () => {
        console.log(commentService);
        expect(typeof commentService).toBe("object");
        expect(commentService instanceof CommentServicer).toBeTruthy();
    });
    describe("Comment 글쓰기", () => {
        it("commentwrite", () => {
            expect(typeof commentService.write).toBe("function");
        });
        it("write 매개변수 잘 작성되어있는가?", async () => {
            //writer, comment boardid
            const data: CommentWriteDTO = {
                writer: "web7722",
                comment: "aaasdd123",
                boardid: 0,
            };

            const result = await commentService.write(data);
            expect(commentRepository.create).toBeCalledWith(data); //호출이 되었는지 확인 하는것, 인자값을 포함한 호출인지
            expect(result).toEqual({ id: 0, writer: "cheol", comment: "asfsafaf", boardid: 0 }); // 리턴값이 이 객체와 같은지 확인
        });
    });
});

 


model >repository > service > controller 순으로 작성하는것이 좋음

 

beforeEach(() => {
    user = new UserController();
}); // 중복된 값이 많이 생겼을 때 쓸 수 있는것
//이벤트 실행 같은 개념 it 이 실행되기 전 때마다 실행
beforeAll(() => {
    //it 함수가 실행되기 전에 딱 한번
    result = { name: "hello world" };
});
afterAll(() => {
    //실행 되고 나서 딱 한번
});
afterEach(() => {
    //실행 될 때마다 계속 
});

 


expect


toBe() 값이 동일한지 확인
toEqual() 두 객체의 값이 같은지 확인 tobe와 다르게 객체를 깊게 비교할 때 사용
toBeCalled() 함수가 호출되었는지를 확인
toBeCalledWith(123) 함수가 특정 인자와 함께 호출되었는지를 확인하는 것
.toBeTruthy() 값이 true인지 확인

 

 

 

.jest.fn() 가상의 함수를 만들어서 실행시키는 역할을 한다.
.mockReturunValue() > 단순한 리턴 값을 받아오는 것
.mockResolvedValue() > promise 리턴 값을 받아오는 것