Jest 2 Matcher
Jest 2 - Matcher
์ฃผ๋ก ํจ์๋ฅผ ๊ฒ์ฌํ๊ฑฐ๋ ๋ชจ๋ํฐ๋ง ํ ๋ ์ฌ์ฉํ๋ Matcher๋ค. ํจ์๋ฅผ ๊ฒ์ฌํ ๋ ๋ React, React Native์์ ์์ฃผ ์ฌ์ฉํ๋ ํ ์ค ๊ธฐ๋ฒ์ธ snapshot์ ์ฌ์ฉํ ๋ ๊ผญ ํ์ํ ๊ธฐ๋ฅ์ด ์๋๋ฐ jest์์ ์ ๊ณตํ๋ mockํจ์๋ค.
์ฌ์ฉ๋ฒ
// ์๋์ ๊ฐ์ด jest.fn()์ผ๋ก ์ฃผ๋ฉด ๋๋ค.
const mockFunction = jest.fn();
// ์๋์ฒ๋ผ return๊ฐ์ ์ง์ ํด ์ค์ ์๋ค
const hasReturn = jest.fn(() => 1);
Matcher
toBeCalled & toHaveBeenCalled
ํธ์ถ ์ฌ๋ถ
const mockFunction = jest.fn();
mockFunction();
test('ํจ์ ํธ์ถ ์ฌ๋ถ', () => {
// ์ด๋ฆ๋ง ๋ค๋ฅด๊ณ ๊ธฐ๋ฅ์ ๋์ผ
expect(mockFunction).toBeCalled();
expect(mockFunction).toHaveBeenCalled();
});
toBeCalledTimes & toBeCalledWith
ํธ์ถ ํ์, ํธ์ถ์ ์ธ์๊ฐ ํ์ธ
const mockFunction = jest.fn();
mockFunction();
test('ํจ์ ํธ์ถ ์ฌ๋ถ', () => {
// ๋ช๋ฒ ํธ์ถ
expect(mockFunction).toBeCalledTimes(1);
// ์ด๋ค ์ธ์ ๊ฐ๊ณผ ํธ์ถ
expect(mockFunction).toBeCalledWith();
});
toReturn & toHaveReturned
return ๊ฐ ํ์ธ
test('ํจ์ ๋ฐํ ์ฌ๋ถ', () => {
const hasReturn = jest.fn(() => 1);
hasReturn();
// ์ด๋ฆ๋ง ๋ค๋ฅด๊ณ ๊ธฐ๋ฅ์ ๋์ผ
expect(hasReturn).toReturn();
expect(hasReturn).toHaveReturned();
});
toReturnTimes & toHaveReturnedTimes
return ํธ์ถ ์ฌ๋ถ
test('ํจ์ ๋ฐํ ์ฌ๋ถ', () => {
const hasReturn = jest.fn(() => 1);
hasReturn();
// ๋น๊ต ๊ฐ์ ๋ช๋ฒ์ ๋ฐํํ๋์ง, ์ด๋ฆ๋ง ๋ค๋ฅด๊ณ ๊ธฐ๋ฅ์ ๋์ผ
expect(hasReturn).toReturnTimes(1);
expect(hasReturn).toHaveReturnedTimes(1);
});
๋น๋๊ธฐ ํจ์ ํ ์คํธ
promise, async & await, callback์ ๊ฒ์ฌํ๊ธฐ
test('done์ ์ด์ฉํด ๊ฒ์ฌํ๊ธฐ', done => {
function callback(data) {
try {
expect(data).toBe('peanut butter');
done();
} catch (error) {
done(error);
}
}
fetchData(callback);
});
test('Promise์์ ๊ฒ์ฌํ๊ธฐ', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});
test('Promise์์ ๊ฒ์ฌํ๊ธฐ', () => {
return expect(fetchData()).resolves.toBe('peanut butter')
});
test('async & await ๊ฒ์ฌํ๊ธฐ', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});
test('async & await ๊ฒ์ฌํ๊ธฐ', async () => {
await expect(fetchData()).resolves.toBe('peanut butter');
});