Jest는 페이스북에서 만들어진 테스팅 라이브러리이다.
npm install -D jest
먼저 간단한 프로젝트를 생성한다.
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
서버가 만들어졌다.
이제 jest
를 설치해야 한다.
npm install -D jest
jest를 설치 후 app.test.js
라는 파일을 만든 후 코드를 작성한다.
describe("plus test", () => {
it("1+2", done => {
expect(1 + 2).toEqual(3);
done();
});
});
코드 작성이 완료되면 package.json
에 script
명령어를 추가한다.
"scripts": {
"test": "jest ./*.test.js"
}
npm run test
명령어를 통해 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인 테스트 케이스를 작성하여 실패한 것을 확인할 수 있다.
먼저 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();
});
});
});
모든 테스트가 통과된 것을 확인할 수 있다.