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('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);
});
소수점은 toEqual 보다 toBeCloseTo를 사용해야 한다.
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'milk',
];
test('the shopping list has milk on it', () => {
expect(shoppingList).toContain('milk');
expect(new Set(shoppingList)).toContain('milk');
});
function 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 a string that must be contained in the error message or a regexp
expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
expect(() => compileAndroidCode()).toThrow(/JDK/);
// Or you can match an exact error message using a regexp like below
expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK$/); // Test fails
expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK!$/); // Test pass
});
npm install @types/jest를 설치하게 되면 test를 올려놓게 되면 type을 확인할 수 있다.
그럼 it의 interface를 볼수 있게 되는데 기본적인 param등에 대해 확인해 볼 수 있다.
param으로 는 name이름과 fn 콜백함수로 전달, timeout 비동기함수에 한해서 얼마만큼의 시간을 허용할것인지 3가지의 param을 제공해 주고 있다.
fn과 timeout은 옵션 인 것도 확인 해볼수 있다. !
jest.config.js에서 collectCoverage 는 기본적으로 true라고 설정되어있다.
만약 npm run test 를 입력했을때 매번 test coverage가 나오길 원하지 않는다면 collectCoverage를 false로 설정 하면 된다.
collectCoverage를 false로 설정해 놓고 따로 test code를 확인하려면 jest —coverage 명령어를 입력하면 coverage를 확인할 수 있다.
매번 명령어를 입력해서 test코드가 성공했는지 실패했는지 확인하는것이 번거롭다면 package.json파일에서 watchAll 을 추가해주면 된다.
"scripts": {
"test": "jest --watchAll"
},
"scripts": {
"test": "jest --watch"
},