프론트엔드 테스트/Jest

[Jest] 자바스크립트 테스트 - Matcher 알아보기

남민섭 2024. 3. 30. 01:14
728x90
반응형

Matcher함수는 테스트 케이스의 예상 결과를 검증하는 함수

Jest에서 제공하는 다양한 Matcher 함수를 사용하면, 값이나

객체의 동등성, 타입, 포함 관계 등을 다양한 방식으로 검사할 수 있음 

 

다양한 Matcher 메서드를 참고할 사이트

https://jestjs.io/docs/expect

 

Expect · Jest

When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things.

jestjs.io

 

실습해본 함수들

toBe 숫자나 문자 등 기본 타입값을 비교될 때 사용
toEqual 객체나 배열과 같은 복합 데이터 타입의 값을 비교할 때 사용
toStrictEqual toEqual 과 비슷하지만 보다 엄격하게 테스트 진행할 때 사용
toBeNull null인지 확인할 때 사용
toBeUndefined undefined 인지 확인할 때 사용
toBeDefined undefined이 아닌지 확인할 때 사용
toBeTruthy true 인지 확인할 때 사용
toBeFalsy false인지 확인할 때 사용
toBeGreaterThan 어떠한 값을 비교했을 때 크면 테스트 통과
toBeGreaterThanOrEqual 어떠한 값을 비교했을 때 크거나 같으면 테스트 통과
toBeLessThan 어떠한 값을 비교했을 때 작으면 테스트 통과
toBeLessThanOrEqual 어떠한 값을 비교했을 때 작거나 같으면 테스트 통과
toBeCloseTo 비교한값에 가까운지 근사치인지 확일할 때 사용
toMatch 문자열이 특정 패턴 또는 정규표현식에 일치하는지 검사할 때 사용
toContain 배열에서 특정 요소 검색할 때 사용
toThrow 어떤 작업을 했을 때 특정 에러가 발생하는지 테스트 할 때

 


toBe

fn.js

const fn = {
  add: (num1, num2) => num1 + num2,
};

module.exports = fs;

 

fn.test.js

const fn = require("./fn");
//expect안에 검증할 값 넣고 toBe안에 기대되는 값을 넣어줌
test("1은 1이야", () => {
  expect(1).toBe(1);
});

test("2 더하기 3은 5야", () => {
  expect(fn.add(2, 3)).toBe(5);
});

test("3 더하기 3은 5가 아니야", () => {
  expect(fn.add(3, 3)).not.toBe(5);
});

 

결과

 

 


toEqual

객체나 배열은 재귀적으로 돌면서 확인해야해서 toEqual을 사용해야함

fn.js

const fn = {
  add: (num1, num2) => num1 + num2,
  makeUser: (name, age) => ({ name, age }),
};

module.exports = fn;

 

fn.test.js

const fn = require("./fn");

test("이름과 나이를 전달받아서 객체를 반환해줘", () => {
  expect(fn.makeUser("Mike", 30)).toBe({
    name: "Mike",
    age: 30,
  });
});

test("이름과 나이를 전달받아서 객체를 반환해줘", () => {
  expect(fn.makeUser("Mike", 30)).toEqual({
    name: "Mike",
    age: 30,
  });
});

 

결과

toEqual로 적용한건 통과

 


toStrictEqual

위 toEqual 결과를 봤을 때 아래와 같은 메세지가 있는데 toStrictEqual을 사용해서 비교해보자

If it should pass with deep equality, replace "toBe" with "toStrictEqual"

fn.js

const fn = {
  add: (num1, num2) => num1 + num2,
  makeUser: (name, age) => ({ name, age, gender: undefined }),
};

module.exports = fn;

 

fn.test.js

const fn = require("./fn");

test("이름과 나이를 전달받아서 객체를 반환해줘", () => {
  expect(fn.makeUser("Mike", 30)).toEqual({
    name: "Mike",
    age: 30,
  });
});

test("이름과 나이를 전달받아서 객체를 반환해줘", () => {
  expect(fn.makeUser("Mike", 30)).toStrictEqual({
    name: "Mike",
    age: 30,
  });
});

 

결과

 

인수로 전달 받은 객체 값,구조 일치해야함


toBeNull

fn.test.js

test("null은 null이다.", () => {
  expect(null).toBeNull();
});

 

결과

 


toBeUndefined

fn.test.js

test("undefined은 undefined이다.", () => {
  expect(undefined).toBeUndefined();
});

 


toBeDefined

fn.test.js

test("변수가 undefined가 아님을 확인", () => {
  const myVariable = "존재하는 값";
  expect(myVariable).toBeDefined();
});

 


toBeFalsy

fn.js

const fn = {
  add: (num1, num2) => num1 + num2,
  makeUser: (name, age) => ({ name, age, gender: undefined }),
};

module.exports = fn;

 

fn.test.js

test("0은 false이다", () => {
  expect(fn.add(1, -1)).toBeFalsy();
});

test("0은 false이다", () => {
  expect(fn.add("hello", "world")).toBeFalsy();
});

 

결과

빈문자열이 아니여서 테스트 실패

 


toBeTruthy

fn.js

const fn = {
  add: (num1, num2) => num1 + num2,
  makeUser: (name, age) => ({ name, age, gender: undefined }),
};

module.exports = fn;

 

fn.test.js

test("0은 false이다", () => {
  expect(fn.add(1, -1)).toBeFalsy();
});

test("빈문자열이 아니면 true이다", () => {
  expect(fn.add("hello", "world")).toBeTruthy();
});

 

결과


 

toBeGreaterThan,

toBeGreaterThanOrEqual,

toBeLessThan,

toBeLessThanOrEqual,

 

fn.test.js

// 실패 테스트 케이스
test("ID는 10자 이하여야한다", () => {
  const id = "THE_BLACK_ORDER";
  expect(id.length).toBeLessThanOrEqual(10);
});

//성공 테스트 케이스
test("ID는 10자 이하여야한다", () => {
  const id = "THE_BLACK";
  expect(id.length).toBeLessThanOrEqual(10);
});

 

결과

실패 케이스
성공 케이스

 


toBeCloseTo

소수점을 테스트 할 때

fn.js

const fn = {
  add: (num1, num2) => num1 + num2,
  makeUser: (name, age) => ({ name, age, gender: undefined }),
};

module.exports = fn;

 

fn.test.js

test("0.1 더하기 0.2 는 0.3 이다", () => {
  expect(fn.add(0.1, 0.2)).toEqual(0.3);
});

 

 

결과

간단하게 컴퓨터는 이진법을 사용하다 보니 이미지처럼 뜬다

 

toBeCloseTo를 사용하면 

fn.test.js

test("0.1 더하기 0.2 는 0.3 이다", () => {
  expect(fn.add(0.1, 0.2)).toBeCloseTo(0.3);
});

 

결과

 


toMatch

정규 표현식 참고 할 것.

fn.test.js

//실패 케이스
test("Hello World에 a라는 글자가 있나?", () => {
  expect("Hello World").toMatch(/a/);
});

// 성공 케이스
test("Hello World에 H라는 글자가 있나?", () => {
  expect("Hello World").toMatch(/H/);
});

 

결과

실패 케이스

 

성공 케이스 H라는 글자 있는지확인


toContain

fn.test.js

test("Mike 있나요?", () => {
  const user = "Mike";
  const userList = ["Tom", "Mike", "Kai"];
  expect(userList).toContain(user);
});

결과


toThrow

fn.js

const fn = {
  add: (num1, num2) => num1 + num2,
  makeUser: (name, age) => ({ name, age, gender: undefined }),
  throwErr: () => {
    throw new Error("xx");
  },
};

module.exports = fn;

 

fn.test.js

//인수 전달 안할 때 어떤 에러든 통과함
test("에러 발생 하나?", () => {
  expect(() => fn.throwErr()).toThrow();
});

//특정 에러에만 통과 되게 하려면 (실패 케이스)
test("에러 발생 하나?", () => {
  expect(() => fn.throwErr()).toThrow("oo");
});

//특정 에러에만 통과 되게 하려면 (성공 케이스)
test("에러 발생 하나?", () => {
  expect(() => fn.throwErr()).toThrow("xx");
});

 

결과

어떤 에러든 통과 케이스
특정 에러에만 통과되게(이미지는 실패케이스)


 

참고 유튜브 영상 - 코딩 앙마

https://youtu.be/_36vt4fBjOQ?si=zl3ImcFWLHNdPntK

 

728x90
반응형