jest Globals API

adam2·2022년 2월 1일
0

Test 뼈대를 구성하는 global api

Before Test

beforeAll(fn, timeout)

해당 파일의 테스트가 실행되기전에 실행된다. 만약 함수가 promise나 generator를 리턴하면 Jest는 테스트를 실행하기 전에 before all의 함수가 resolve될 때 까지 기다린다. timeout을 설정 할 수 있고, default timeout은 5초이다.
테스트에서 사용될 여러 글로벌 state를 셋업할 때 사용하면 좋다.

만약 테스트 함수를 실행할 때 마다 무언가를 실행하려면 beforeEach를 사용한다.

const globalDatabase = makeGlobalDatabase();

beforeAll(() => {
  // Clears the database and adds some testing data.
  // Jest will wait for this promise to resolve before running tests.
  return globalDatabase.clear().then(() => {
    return globalDatabase.insert({testData: 'foo'});
  });
});

// Since we only set up the database once in this example, it's important
// that our tests don't modify it.
test('can find things', () => {
  return globalDatabase.find('thing', {}, results => {
    expect(results.length).toBeGreaterThan(0);
  });
});

만약 describe블록 안에 beforeAll이 있다면, describe block의 시작 부분에서 시작된다.

beforeEach(fn, timeout)

해당 파일의 테스트 함수를 실행할 때마다 함수를 실행한다. beforeAll과 동일하게 promise나 generater 함수인 경우 resolve할 때 까지 기다리고, default timeout 시간도 같다.

const globalDatabase = makeGlobalDatabase();

beforeEach(() => {
  // Clears the database and adds some testing data.
  // Jest will wait for this promise to resolve before running tests.
  return globalDatabase.clear().then(() => {
    return globalDatabase.insert({testData: 'foo'});
  });
});

test('can find things', () => {
  return globalDatabase.find('thing', {}, results => {
    expect(results.length).toBeGreaterThan(0);
  });
});

test('can insert a thing', () => {
  return globalDatabase.insert('thing', makeThing(), response => {
    expect(response.success).toBeTruthy();
  });
});

test 실행하기

describe(name, fn)

테스트 단위를 묶는 가장 큰 단위이다. 테스트 시 describe에 설명된 내용으로 테스트 단위를 크게 분류 해준다.
deescribe는 필수는 아니지다. 최상위 블록에서 test()를 바로 사용할 수 있지만 test들을 그룹으로 구성하려면 사용한다.

아래 예시처럼 test에 계층이 있는 경우 describe 블록을 중첩해서 사용할 수 있다.

const binaryStringToNumber = binString => {
  if (!/^[01]+$/.test(binString)) {
    throw new CustomError('Not a binary number.');
  }

  return parseInt(binString, 2);
};

describe('binaryStringToNumber', () => {
  describe('given an invalid binary string', () => {
    test('composed of non-numbers throws CustomError', () => {
      expect(() => binaryStringToNumber('abc')).toThrowError(CustomError);
    });

    test('with extra whitespace throws CustomError', () => {
      expect(() => binaryStringToNumber('  100')).toThrowError(CustomError);
    });
  });

  describe('given a valid binary string', () => {
    test('returns the correct number', () => {
      expect(binaryStringToNumber('100')).toBe(4);
    });
  });
});

test(name, fn, timeout)

it()과 동일한 역할을 한다. testit의 기능적 차이는 없지만 it의 경우 다른 테스트 프레임워크에서 많이 사용하기 때문에 넣었다고 한다.

name: 테스트 이름
fn: 테스트 함수
timeout: 타임아웃(The default timeout is 5 seconds)

test에서 promise가 리턴되면, jest는 promise가 resolve될 때 까지 기다린다.

test('has lemon in it', () => {
  return fetchBeverageList().then(list => {
    expect(list).toContain('lemon');
  });
});

기타

describe.each(table)(name, fn, timeout)

다른 데이터로 같은 test를 진행해야할 때 사용한다.

describe.only(name, fn)

해당 describe블록만 실행하고 싶을 때 사용한다

describe.only.each(table)(name, fn)

해당 describe 블록만 여러 데이터로 테스트하고싶을 때 사용한다.

describe.skip(name, fn)

해당 describe 블록을 실행하고 싶지 않을 때 사용한다.

test.concurrent(name, fn, timeout)

테스트를 동시에 실행할 때 사용한다. experimental 기능이므로 사용시엔 주의해서 사용한다.

Test 마무리하기

afterAll(fn, timeout)

beforeAll과 동일하게 모든 테스트가 종료되고 마지막에 한번 실행된다.

const globalDatabase = makeGlobalDatabase();

function cleanUpDatabase(db) {
  db.cleanUp();
}

afterAll(() => {
  cleanUpDatabase(globalDatabase);
});

test('can find things', () => {
  return globalDatabase.find('thing', {}, results => {
    expect(results.length).toBeGreaterThan(0);
  });
});

test('can insert a thing', () => {
  return globalDatabase.insert('thing', makeThing(), response => {
    expect(response.success).toBeTruthy();
  });
});

afterEach(fn, timeout)

beforeEach와 동일하게 모든 test 함수가 종료될 때 마다 실행된다.

const globalDatabase = makeGlobalDatabase();

function cleanUpDatabase(db) {
  db.cleanUp();
}

afterEach(() => {
  cleanUpDatabase(globalDatabase);
});

test('can find things', () => {
  return globalDatabase.find('thing', {}, results => {
    expect(results.length).toBeGreaterThan(0);
  });
});

test('can insert a thing', () => {
  return globalDatabase.insert('thing', makeThing(), response => {
    expect(response.success).toBeTruthy();
  });
});

0개의 댓글