Programming/Javascript

Chai - should, expect, assert

c29130811 2024. 6. 10. 12:02

예제 함수로 공백을 제거하는 게 있다고 치자!

function removeSpaces(str) {
  return str.replace(/\s+/g, '');
}

 

assert 

assert 는 Node.js의 기본 assert 모듈과 유사한 방법으로 작동으로 함수의 인자에 기대값과 실제값을 전달

import * as chai from 'chai';
import { removeSpaces } from '../index.js';

const { assert } = chai;

describe('removeSpaces with Assert', () => {

    it('가운데 공백 제거', () => {
        const input = 'Hello World';
        const expectedOutput = 'HelloWorld';
        assert.equal(removeSpaces(input), expectedOutput);
    });
    
    ...
});
 

expect

expect 은 체이닝(chaining)을 사용.

import * as chai from 'chai';
import { removeSpaces } from '../index.js';

const { expect } = chai;

describe('removeSpaces with Expect', () => {

    it('가운데 공백 제거', () => {
        const input = 'Hello World';
        const expectedOutput = 'HelloWorld';
        const result = removeSpaces(input);
        expect(result).to.be.a('string');
        expect(result).to.equal(expectedOutput);
    });
    ...
    
});

 

should

should 객체 프로토타입에 should를 추가하여 동작.

import * as chai from 'chai';
import { removeSpaces } from '../index.js';

const should = chai.should();

describe('removeSpaces with Should', () => {

    it('가운데 공백 제거', () => {
        const input = 'Hello World';
        const expectedOutput = 'HelloWorld';
        const result = removeSpaces(input);
        result.should.be.a('string');
        result.should.equal(expectedOutput);
    });
    ...
});

 

should를 사용할때 () 실행할 값을 저장하여 사용한다.

 

 

참고: https://www.chaijs.com/guide/styles/#differences

 

Assertion Styles - Chai

Assertion Styles This section of the guide introduces you to the three different assertion styles that you may use in your testing environment. Once you have made your selection, it is recommended that you look at the API Documentation for your selected st

www.chaijs.com

 

728x90

'Programming > Javascript' 카테고리의 다른 글

Jest, Mocha, Chai  (0) 2024.06.08
push pop shift unshift  (0) 2022.12.04
Array 랜덤 배열  (0) 2022.05.02
익명함수와 즉시 실행 함수  (0) 2021.05.29
함수 호출 및 return  (0) 2021.05.21