// yarn add --dev jest
// npm install --save-dev jest
function sum(a,b) {
return a + b;
}
module.exports = sum;
//
{
"scripts": {
"test": "jest"
}
}
// jest my-test --notify --config=config.json
jest --init
yarn add --dev babel-jest @babel/core @babel/preset-env
jest --init
yarn add --dev babel-jest @babel/core @babel/preset-env
// babel.config.js
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};
값을 가장 간단하게 테스트하려면 완전히 같은 값을 테스트하면 쉽다.
test('two plus two is four', ()=> {
expect(2 + 2).toBe(4);
});
// opposite
test('adding positive numbers is not zero', ()=> {
for(let a = 1; a < 10; a++) {
for(let b = 1; b < 10; b++) {
expect(a + b).not.toBe(0);
}
}
});
test('null', ()=> {
const n = null;
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
expect(n).toBeFalsy();
});
test('zero', ()=> {
const z = 0;
expect(z).not.toBeNull();
expect(z).toBeDefined();
expect(z).not.toBeUndefined();
expect(z).not.toBeTruthy();
expect(z).toBeFalsy();
숫자를 비교하는 대부분의 방법은 대응하는 매처가 존재합니다.
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4);
expect(value).toEqual(4);
});
실수의 비교를 위해서는 toBeEqual 대신에 toBeCloseTo를 사용해야합니다.
문자열에 대해서는 정규표현식과 toMatch를 사용해서 일치를 확인할 수 있습니다.
test('there is no I in team`, () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => { expect('Christoph').toMatch(/stop/);
});
배열과 이터러블이 특정한 아이템을 가지고 있는지 toContain을 통해서 확인할 수 있습니다.
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'milk',
];
tst('the shopping list has milk on it', () => {
expect(shppingList).toContain('milk');
expect(new Set(shoppingList)).toContain('milk');
});
만약 당신이 특정한 함수가 호출되었을때 에러가 발생하는지 확인하려면, toThrow를 쓰세요
fucntion compileAndroidcode() {
throw new Error('you are using the wrong JDK');
}
test('compiling android goes as expected', () => {
expect(() => compileAndroidcode()).toThrow();
expect(() => compileAndroidCode()).toThrow(Error);
// You can also use the exact error message or a regexp
expect(() => compileAndroidCode()).toThrow('your are using the wrong JDK');
expect(() => compileAndroidCode()).toThrow(/JDK/);
});
맛보기일뿐입니다. 매처의 리스트를 더보기 원하시면 reference docs를 보십시오