티스토리 뷰

프로그램 개발을 할 때 단위 테스트라는걸 사용한다고 한다.

말 그대로 작성한 프로그램에 대한 테스트를 진행하는건데, 사실 얘를 들은게 이번이 처음은 아니다.

이런게 있다고 수도 없이 많이 들었고, 코테에서 단위 테스트를 진행하는 기업들도 있어서 낯선 이름은 아니다.

그런데 솔직히 얘를 왜 해야 하는지 100% 이해하는건 아니다.

어차피 프로그램 작성은 해야 하는 일이고, 프로그램이 동작하다가 원하는 흐름대로 되지 않으면 console.log나 break point 걸어두고 테스트 해보면 다 해결 되는 일 아닌가?

하지만 이름 있는 개발자들이 중요하다고 하는데는 이유가 있겠지. 한 번 해보기로 한다.

 

대충 이런 구조의 프로젝트를 만든다.

이번 프로젝트에서 사용해볼 단위 테스트 라이브러리는 Jest인데, 모든 단위 테스트 라이브러리가 그런건진 모르겠지만 파일 이름 끝에 .test를 붙여줘야 동작한다.

테스트를 진행할 파일들을 명시해줘야 하니까 당연한거겠지.

 

app.test.js / package.json

간단하게 위처럼 작성해주고, 터미널에서

yarn test

를 실행한다.

테스트 결과

테스트가 진행되어 통과 된 것을 볼 수 있다.

테스트 파일에 작성하는 함수들은 몇 가지가 있는데,

describe(name, fn) - 테스트를 진행할 그룹을 생성함.
test(name, fn) - 실제로 테스트를 진행할 단위
expect(value) - 비교 대상이 될 값을 value에 삽입하는 함수
expect(value).toBe(value) - expect의 value가 toBe의 value와 일치하면 테스트 통과

이런게 있다. 실제로는 더 많은데 일단 기본적으로는 이것만 알고 있으면 될 듯.

expect에 따라붙는 메소드에는 toBe 말고도 아래와 같이 많은 메소드가 존재한다.

.not - 테스트 조건을 반대로 기재할 때
.resolves - Promise로부터 넘어오는 값을 비교할 때
.rejects - Promise로부터 넘어오는 에러를 비교할 때
.toBe(value) - 기대값이 동일하다면 테스트 통과
.toHaveBeenCalled() - 함수가 실행된 적이 있는지 테스트하고, 실행된 적이 있다면 통과
.toHaveBeenCalledTimes(number) - 함수가 실행된 횟수를 테스트하고, 일치하다면 통과
.toHaveBeenCalledWith(arg1, arg2, ...) - 특정 매개변수를 토대로 함수가 실행 되었는지 테스트
.toHaveBeenLastCalledWith(arg1, arg2, ...) - 마지막으로 호출 된 매개변수 테스트
.toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....)
.toHaveReturned()
.toHaveReturnedTimes(number)
.toHaveReturnedWith(value)
.toHaveLastReturnedWith(value)
.toHaveNthReturnedWith(nthCall, value)
.toHaveLength(number)
.toHaveProperty(keyPath, value?)
.toBeCloseTo(number, numDigits?)
.toBeDefined()
.toBeFalsy()
.toBeGreaterThan(number | bigint)
.toBeGreaterThanOrEqual(number | bigint)
.toBeLessThan(number | bigint)
.toBeLessThanOrEqual(number | bigint)
.toBeInstanceOf(Class)
.toBeNull()
.toBeTruthy()
.toBeUndefined()
.toBeNaN()
.toContain(item)
.toContainEqual(item)
.toEqual(value)
.toMatch(regexp | string)
.toMatchObject(object)
.toMatchSnapshot(propertyMatchers?, hint?)
.toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot)
.toStrictEqual(value)
.toThrow(error?)
.toThrowErrorMatchingSnapshot(hint?)
.toThrowErrorMatchingInlineSnapshot(inlineSnapshot)

여러가지가 있지만 그 중에서 가장 많이 쓰는 메소드는 아래 정도다.

.toBeDefined()
.toBeFalsy()
.toBeGreaterThan(number | bigint)
.toBeGreaterThanOrEqual(number | bigint)
.toBeLessThan(number | bigint)
.toBeLessThanOrEqual(number | bigint)
.toBeInstanceOf(Class)
.toBeNull()
.toBeTruthy()
.toBeUndefined()
.toBeNaN()
.toContain(item)
.toContainEqual(item)
.toEqual(value)
.toMatch(regexp | string)

값을 비교하고, 변수가 존재하는지 확인하는 등의 함수라서 가장 많이 쓰일 것 같다.

LIST

'기술 및 이슈' 카테고리의 다른 글

husky를 이용한 자동 테스트 맛보기 - 1  (0) 2021.08.10
[수학] Sine Graph  (0) 2020.11.12
정규표현식이란?  (0) 2020.06.13
Restful API란?  (0) 2020.05.25
웹앱의 퍼포먼스를 늘리는 법  (0) 2020.05.22