TIL(20.02.28) JavaScript 유닛 테스트 프레임 워크 Mocha,단언 라이브러리 chai

이민택·2020년 2월 28일
0

TIL

목록 보기
13/44

Mocha

Mocha 프레임워크는 javascript의 테스트 코드 작성을 도와주는 프레임워크이다 다음 기본적인 테스트 코드를 보자

var assert = require('assert');

describe('#Hello World!', function () {
    it('입력 값은 Hello World!', function () {
        var input = 'Hello World!'; // 입력 값이라고 가정

        assert.equal('Hello World!', input);
    });
});

describe()를 이용하여 테스트를 정의하고 it()을 이용하여 유닛테스트를 실행한다.

describe()

테스트를 정의하는 describe()에는 여러개의 describe() 를 가질 수 있고 이 안에서 it()을 이용해서 유닛테스트를 진행 할 수있다

var assert = require('assert');
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal([1, 2, 3].indexOf(4), -1);
    });
  });
});

it()

it() 부분에서는 유닛테스트가 이루어 지는데 이 유닛테스트는 Assertion이라는 개념으로 이루어져 있다 이는 프로그래머가 가정한 주장이 유닛에서 나온 결과가 일치하는지 테스트 하는 것이다

chai

chai는 단언(Assertions) 라이브러리 이다 위 it() 내부에서 사용할 수 있고 여러가지 assertion 라이브러리를 가지고 있다 자주 사용하느 단언문은 아래와 같다

  • should : BDD 스타일의 개발을 할 때 사용하는 assertions 이다
var should = require('chai').should() //actually call the function
  , foo = 'bar'
  , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };

foo.should.be.a('string');
foo.should.equal('bar');
foo.should.have.lengthOf(3);
beverages.should.have.property('tea').with.lengthOf(3);
Differences
  • Expect : should와 같이 BDD스타일에 사용한다 Expect는 실패했을 경우 메세지를 매개변수로 담을 수 있다
var expect = require('chai').expect
  , foo = 'bar'
  , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };

expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
expect(foo).to.have.lengthOf(3);
expect(beverages).to.have.property('tea').with.lengthOf(3);

// AssertionError: expected 43 to equal 42.
expect(answer).to.equal(42);

// AssertionError: topic [answer]: expected 43 to equal 42.
expect(answer, 'topic [answer]').to.equal(42);
  • Assert :TDD 스타일의 assertion으로써 기본적인 dot notation을 이용하여 api를 사용할 수 있다
var assert = require('chai').assert
  , foo = 'bar'
  , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };

assert.typeOf(foo, 'string'); // without optional message
assert.typeOf(foo, 'string', 'foo is a string'); // with optional message
assert.equal(foo, 'bar', 'foo equal `bar`');
assert.lengthOf(foo, 3, 'foo`s value has a length of 3');
assert.lengthOf(beverages.tea, 3, 'beverages has 3 types of tea');
profile
데이터에 소외된 계층을 위해 일을 하는 개발자를 꿈꾸는 학생입니다

0개의 댓글