단위 테스트를 위한 Jest 연동

He SEO·2022년 4월 26일
0
post-thumbnail

Jest

Meta에서 유지 관리하는 Javascript 테스트 프레임워크

1. Install Jest

npm 혹은 yarn으로 설치할 수 있다. 여기서는 npm을 사용한다.

npm install --save-dev jest

2. Create functions

두개의 임의의 function을 생성하여 테스트 해본다.

Function #1

두 파라미터를 더하는 add.js 파일 생성

function add(a, b) {
    return a + b
}
module.exports = add

Function #2

나이를 받아 아이인지 확인하는 child.js 파일 생성. 입력된 나이가 18 초과하면 어른이므로 false, 이하면 true를 반환한다.

function child(age) {
    if (age > 18) return false
    else return true 
}

module.exports = child

3. Create test file

테스트를 위한 app.test.js 파일 생성

const add = require('./add')
const child = require('./child')

describe('Start test', () => {
  test('add numbers', () => {
    expect(add(1, 2)).toBe(3)
    //expect(function(파라미터1, 파라미터2)).toBe(예상되는 결과값)
  })
  
  test('isChild?', () => {
    expect(child(13)).toBeTruthy
  })
})

4. Change package.json

package.json 파일에서 jest를 사용하도록 변경한다.
--verbose 옵션을 넣으면 상세 로그를 출력할 수 있다.

"scripts": {
    "test": "jest --verbose",
}

5. Execute

npm test 

6. Result

 PASS  ./app.test.js
  Start testadd numbers (1 ms)
    ✓ isChild?

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.215 s, estimated 1 s

참고 사이트

profile
BACKEND 개발 기록 중. 감사합니다 😘

0개의 댓글