Jest
Jest는 단순성에 중점을두고 Facebook, Inc.에서 유지 관리하는 JavaScript 테스트 프레임 워크입니다. Babel, TypeScript, Node.js, React, Angular, Vue.js 및 Svelte를 사용하는 프로젝트에서 작동합니다.
Categories
- jest.config.js
- ts-jest
- Jest:Mock (Jest.mock)
- Jest:Mock:Axios - jest에서 axios mockup 테스트 방법.
About
페이스북에서는 Jest를 단순한 테스팅 라이브러리가 아닌 “테스팅 프레임워크”라고 부르는 만큼 기존 자바스크립트 테스팅 라이브러리와는 차별점이 있습니다. Jest 이전에는 자바스크립트 코드를 테스트하라면 여러가지 테스팅 라이브러리를 조합해서 사용하곤 했었습니다. 예를 들어, Mocha나 Jasmin을 Test Runner로 사용하고, Chai나 Expect와 같은 Test Mathcher를 사용했으며, 또한 Sinon과 Testdouble 같은 Test Mock 라이브러리도 필요했었습니다. 이 라이브러리들은 굉장히 유사하지만 살짝씩 다른 API를 가지고 있었기 때문에, 여러 프로젝트에 걸쳐서 일하는 자바스크립트 개발자들에게 혼란을 주기도 했었습니다. 하지만 Jest는 라이브러리 하나만 설치하면, Test Runner와 Test Mathcher 그리고 Test Mock 프레임워크까지 제공해주기 때문에 상당히 편리하게 느껴지는 것 같습니다.
Installation
Jest 설치:
babel과 함께 사용할 경우 babel-jest도 설치 1
TypeScript 코드를 테스트할 경우 ts-jest도 설치
테스트 유닛 작성시 jest의 타입 정보 제공을 위해 @types/jest도 함께 설치
With webpack
Options
Isolated Modules option in TypeScript
ts-jest#Isolated Modules option 항목 참조.
Basic syntax
Async test
test('the data is peanut butter', async () => {
await expect(fetchData()).resolves.toBe('peanut butter');
});
Error Type test
test("Test description", () => {
const t = () => {
throw new TypeError("UNKNOWN ERROR");
};
expect(t).toThrow(TypeError);
expect(t).toThrow("UNKNOWN ERROR");
});
Promise test
resolves
를 사용하면 된다.
it('works with resolves', () => {
expect.assertions(1);
return expect(user.getUserName(5)).resolves.toEqual('Paul');
});
실패한 Promise의 경우, 반대로 rejects
를 사용하면 된다.
// Testing for async errors using `.rejects`.
it('tests error with rejects', () => {
expect.assertions(1);
return expect(user.getUserName(3)).rejects.toEqual({
error: 'User with 3 not found.',
});
});
// Or using async/await with `.rejects`.
it('tests error with async/await and rejects', async () => {
expect.assertions(1);
await expect(user.getUserName(3)).rejects.toEqual({
error: 'User with 3 not found.',
});
});
async/await test
// async/await can be used.
it('works with async/await', async () => {
expect.assertions(1);
const data = await user.getUserName(4);
expect(data).toEqual('Mark');
});
// async/await can also be used with `.resolves`.
it('works with async/await and resolves', async () => {
expect.assertions(1);
await expect(user.getUserName(5)).resolves.toEqual('Paul');
});
Subprocess server test
Troubleshooting
document is not defined
- ReferenceError: document is not defined · Issue #422 · testing-library/react-testing-library
- Configuring Jest · Jest # testenvironment-string
다음과 같은 에러가 출력된다면:
jest.config.js파일에 다음 내용을 추가하자.
Test environment jest-environment-jsdom cannot be found
Error: Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration option points to an existing node module.
jest-environment-jsdom을 설치하자.
toThrow 에서 모든 타입이 Error 타입으로 처리될 때
JavaScript:Object#Object prototype mismatch항목 참조.
TypeScript isolatedModules Error
TypeScript에서 jest를 사용할 경우 import 를 사용하지 않아 발생되는 isolatedModules 관련 에러는 다음과 같이 해결:
import {describe, expect, test} from '@jest/globals';
import {sum} from './sum';
describe('sum module', () => {
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
});
See also
- Node.js
- vue-i18n-jest - vue i18n, jest, vue test utils 를 조합한 테스트 방법.