JEST - 자바스크립트 유닛 테스트

이재익·2020년 1월 19일
1

JEST란?


Jest는 페이스북에서 만들어진 테스팅 라이브러리이다.

설치 방법


npm install -D jest

사용 방법


1. 프로젝트 생성

먼저 간단한 프로젝트를 생성한다.

mkdir jestTest
cd jestTest
npm init -y
npm install express

위의 명령어를 통해 express 프로젝트를 만들 준비를 한다.

const express = require("express");

const app = express();

app.get("/hello", (req, res) => {
  return res.json("world");
});

app.listen(5000, () => {
  console.log("hi");
});

get 메소드 '/hello' url로 요청을 보내면 "world"를 response로 반환하는 아주 간단한 express 서버가 만들어졌다.

2. Jest 설치

이제 jest를 설치해야 한다.

npm install -D jest

3. Jest 코드 작성

jest를 설치 후 app.test.js 라는 파일을 만든 후 코드를 작성한다.

describe("plus test", () => {
  it("1+2", done => {
    expect(1 + 2).toEqual(3);
    done();
  });
});

코드 작성이 완료되면 package.jsonscript 명령어를 추가한다.

"scripts": {
    "test": "jest ./*.test.js"
  }

4. Jest 실행 (테스트 통과)

npm run test

명령어를 통해 Jest를 실행하여 테스트를 진행한다.

테스트가 통과가 된 것을 확인할 수 있다.

5. Jest 실행 (테스트 실패)

describe("plus test", () => {
  it("1+2", done => {
    expect(1 + 2).toEqual(3);
    done();
  });

  it("1+1", done => {
    expect(1 + 1).toEqual(3);
    done();
  });
});

1+1인 테스트 케이스를 작성하여 실패한 것을 확인할 수 있다.

6. express 서버와 연동하여 테스트

먼저 npm 모듈supertest를 설치한다.

npm install -D supertest
const app = require("./app");
const request = require("supertest");

describe("express test", () => {
  it("hello world Test", done => {
    request(app)
      .get("/hello")
      .then(res => {
        expect(res.text).toEqual("world");
        done();
      });
  });
});

express 서버로 요청을 보내 전달 받은 response를 확인한다.

테스트가 통과된 것을 확인할 수 있다.

api를 하나 더 추가해 테스트를 진행한다.

const express = require("express");

const app = express();

app.get("/hello", (req, res) => {
  return res.send("world");
});

app.get("/bye", (req, res) => {
  return res.send("world");
});

app.listen(3000);

module.exports = app;
const app = require("./app");
const request = require("supertest");

describe("express test", () => {
  it("hello world Test", done => {
    request(app)
      .get("/hello")
      .then(res => {
        expect(res.text).toEqual("world");
        done();
      });
  });

  it("bye world Test", done => {
    request(app)
      .get("/bye")
      .then(res => {
        expect(res.text).toEqual("world");
        done();
      });
  });
});

모든 테스트가 통과된 것을 확인할 수 있다.

profile
열정 있는 개발자

0개의 댓글