bytrustu tech blog

[Jest] Matchers 사용하기 본문

TDD

[Jest] Matchers 사용하기

bytrustu 2022. 12. 18. 03:26
Jest Matchers 사용법에 대해 알아보자.

 

https://jestjs.io/docs/using-matchers

 

Using Matchers · Jest

Jest uses "matchers" to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the expect API doc.

jestjs.io

 

Common Matchers

toBe: 사용하는 코드가 정확하게 값을 체크한다. loop 중 내용도 모두 체크 가능하다.

test('2+2 의 결과는 4이다.', () => {
    expect(2 + 2).toBe(4);
});

test('Array loop 중 값을 체크한다', () => {
    const data = [1, 1, 1];
    data.forEach((item) => {
        expect(item).toBe(1);
    });
});

toEqual: Object와 Array 값을 체크한다. loop 중 내용도 모두 체크 가능하다.

test('Object 값을 체크한다', () => {
    const data = { one: 1 };
    data['two'] = 2;
    expect(data).toEqual({ one: 1, two: 2 });
});

test('Array 값을 체크한다', () => {
    const data = [1, 2, 3];
    expect(data).toEqual([1, 2, 3]);
});

test('Array loop 중 Object 값을 체크한다', () => {
    const data = [{ a: 1 }, { a: 1 }, { a: 1 }];
    data.forEach((item) => {
        expect(item).toEqual({ a: 1 });
    });
});

not: 부정을 체크한다.

test('2+2 의 결과는 5가 아니다.', () => {
    expect(2 + 2).not.toBe(5);
});

 

Truthiness

toBeNull: null을 체크한다.

toBeUndefined: undefined를 체크한다.

toBeDefined: 값이 정의되어 있는지 체크한다.

toBeTruthy: 값이 참인지 체크한다.

toBeFalsy: 값이 거짓인지 체크한다.

test('null 의 Truthiness를 체크 한다.', () => {
    const n = null;
    expect(n).toBeNull();
    expect(n).toBeDefined();
    expect(n).not.toBeUndefined();
    expect(n).not.toBeTruthy();
    expect(n).toBeFalsy();
});

test('zero의 Truthiness를 체크 한다.', () => {
    const z = 0;
    expect(z).not.toBeNull();
    expect(z).toBeDefined();
    expect(z).not.toBeUndefined();
    expect(z).not.toBeTruthy();
    expect(z).toBeFalsy();
});

 

Numbers

toBeGreaterThan: 숫자가 더 큰지 체크한다.

toBeGreaterThanOrEqual: 숫자가 더 크거나 같은지 체크한다.

toBeLessThan: 숫자가 더 작은지 체크한다.

toBeLessThanOrEqual: 숫자가 더 작거나 같은지 체크한다.

toBeCloseTo: 소수점의 연산을 체크하며 toBe와 toEqual의 경우 오류를 발생하니 주의한다.

test('Numbers를 체크 한다.', () => {
    const value = 2 + 2;
    expect(value).toBeGreaterThan(3);
    expect(value).toBeGreaterThanOrEqual(4);
    expect(value).toBeLessThan(5);
    expect(value).toBeLessThanOrEqual(4);

    expect(value).toBe(4);
    expect(value).toEqual(4);
    expect(0.1 + 0.2).toBeCloseTo(0.3);
})

 

Strings

toMatch: String 타입을 정규표현식으로 체크한다.

test('Strings를 체크한다.', () => {
    expect('team').not.toMatch(/I/);
    expect('ssteamss').toMatch(/team/);
});

 

Arrays and iterables

toContain: 배열 또는 이 트러블 한 객체에 포함된 값을 체크한다.

const animalList = [
  'dog',
  'cat',
  'birt',
  'tiger',
  'lion',
];

test('Arrays and iterables를 체크한다.', () => {
  expect(animalList).toContain('dog');
  expect(new Set(animalList)).toContain('cat');
});

 

Exceptions

toThrow: 오류가 발생했는지 체크한다.

test('Exceptions를 체크한다.', () => {
    expect(() => { throwErrorCode(); }).toThrow();
    expect(() => throwErrorCode()).toThrow(Error);
    expect(() => throwErrorCode()).toThrow('오류가 발생 했습니다!');
    expect(() => throwErrorCode()).toThrow(/오류가/);
    expect(() => throwErrorCode()).toThrow(/^오류가 발생 했습니다!$/);
});

 

계산기 구현 테스트

위 Machers를 활용해서 계산기를 구현해보자.

class Calculator {
    constructor() {
        this.value = 0;
    }

    set(num) {
        this.value = num;
    }

    clear() {
        this.value = 0;
    }

    add(num) {
        const sum = this.value + num;
        if (sum > 100) {
            throw new Error('값은 100을 넘을수 없습니다.');
        }
        this.value = sum;
    }

    subtract(num) {
        this.value = this.value - num;
    }

    multiply(num) {
        this.value = this.value * num;
    }

    divide(num) {
        this.value = this.value / num;
    }
}

module.exports = Calculator;
const Calculator = require('../calculator');

describe('calculator를 테스트 합니다.', () => {
    let cal;
    beforeEach(() => {
        cal = new Calculator();
    });

    test('1+2의 결과는 3이다.', () => {
        cal.set(1);
        cal.add(2);
        expect(cal.value).toBe(3);
    });

    test('더하기의 결과가 100이 넘을 경우 오류를 발생한다.', () => {
       cal.set(99);
        expect(() => cal.add(2)).toThrow();
        expect(() => cal.add(2)).toThrowError('값은 100을 넘을수 없습니다.')
    });

    test('1-1의 결과는 0이다.', () => {
        cal.set(1);
        cal.subtract(1);
        expect(cal.value).toBe(0);
    });

    test('1*10의 결과는 10이다.', () => {
        cal.set(1);
        cal.multiply(10);
        expect(cal.value).toBe(10);
    });

    test('10/2의 결과는 5이다.', () => {
        cal.set(10);
        cal.divide(2);
        expect(cal.value).toBe(5);
    });

    test('0/0의 결과는 NaN이다.', () => {
        cal.set(0);
        cal.divide(0);
        expect(cal.value).toBeNaN();
    });

    test('1/0의 결과는 Infinity이다.', () => {
       cal.set(1);
       cal.divide(0);
       expect(cal.value).toBe(Infinity);
    });
});

'TDD' 카테고리의 다른 글

[Jest] Mock  (0) 2022.12.21
[Jest] 비동기 테스트 하기  (0) 2022.12.19
[Jest] 초기 환경설정  (0) 2022.12.17
Comments