
Jest ๊ณต์ ๋ฌธ์ ์ฐธ๊ณ : https://jestjs.io/docs/expect#reference
Modifier(์์ ์)๋ Jest์์ ๋งค์ฒ์ ๋์์ ๋ฐ๊พธ๋ ์์ฑ์ด๋ค.
์ฆ, expect()๊ฐ ๋ฐํํ๋ Expectation ๊ฐ์ฒด์ ๋ถ์ด์
๋งค์ฒ์ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ์ ์ํค๊ฑฐ๋ ๋น๋๊ธฐ ์ฒ๋ฆฌ๋ฅผ ๊ธฐ๋ค๋ฆฌ๋๋ก ๋ง๋ค์ด์ค๋ค.
expect(value)
.not.toBe(...) // ๊ฒฐ๊ณผ ๋ฐ์
.resolves.toEqual(...) // Promise resolve ๊ฒ์ฆ
.rejects.toThrow(...) // Promise reject ๊ฒ์ฆ
not โ ๊ฒฐ๊ณผ ๋ฐ์ not์ ๋งค์ฒ์ ๋น๊ต ๊ฒฐ๊ณผ๋ฅผ ๋ฐ๋๋ก ๋ค์ง๋๋ค.
์ฆ, โ~์ด ์๋๋คโ๋ฅผ ํ
์คํธํ๊ณ ์ถ์ ๋ ์ฌ์ฉํ๋ค.
expect(2 + 2).not.toBe(5);
expect(['apple', 'banana']).not.toContain('orange');
์ด ๊ตฌ๋ฌธ์ ์ฝ์ผ๋ฉด
โ2 ๋ํ๊ธฐ 2๋ 5๊ฐ ์๋๋ค.โ
โ๋ฐฐ์ด์ orange๋ ํฌํจ๋์ด ์์ง ์๋ค.โ
์ฒ๋ผ ๋ฌธ์ฅ์ผ๋ก ์์ฐ์ค๋ฝ๊ฒ ์ฝํ๋ ํ ์คํธ๊ฐ ๋๋ค.
resolves โ Promise๊ฐ ์ฑ๊ณต์ ์ผ๋ก ์ดํ(resolve)๋ ๊ฒ์ ๊ธฐ๋๋น๋๊ธฐ ํ
์คํธ์์, resolves๋
Promise๊ฐ ์ ์์ ์ผ๋ก resolve๋์ด ๋ฐํ๋ ๊ฐ์ ๊ฒ์ฆํ ๋ ์ฌ์ฉํ๋ค.
์ฆ,
"์ด Promise๋ ์ฑ๊ณต์ ์ผ๋ก ๋๋์ผ ํ๋ฉฐ, ๊ฒฐ๊ณผ๊ฐ์ โฆ์ด๋ค."
๋ฅผ ํํํ๋ ๊ตฌ๋ฌธ์ด๋ค.
const fetchData = () => Promise.resolve({ status: 'ok', data: [1, 2, 3] });
test('fetchData๊ฐ ์ ์์ ์ผ๋ก ์๋ฃ๋์ด status๊ฐ ok์ฌ์ผ ํ๋ค', async () => {
await expect(fetchData()).resolves.toEqual(
expect.objectContaining({ status: 'ok' })
);
});
์ ์ฝ๋๋ ๋ด๋ถ์ ์ผ๋ก ์๋์ ๋์ผํ ์๋ฏธ๋ค ๐
const result = await fetchData();
expect(result).toEqual(expect.objectContaining({ status: 'ok' }));
โ ์์ฝ
await expect(Promise).resolves.๋งค์ฒ() await๋ฅผ ๋ฐ๋์ ๋ถ์ฌ์ผ ํจ (ํ
์คํธ ์ข
๋ฃ ํ์ด๋ฐ ์ค์)rejects โ Promise๊ฐ ์คํจ(reject)๋ ๊ฒ์ ๊ธฐ๋๋น๋๊ธฐ ๋ก์ง์ด ์คํจํ ๊ฒ์ผ๋ก ์์๋ ๋,
๊ทธ reject๋ ์ด์ (์๋ฌ ๊ฐ์ฒด) ๋ฅผ ๊ฒ์ฆํ ์ ์๋ค.
์ฆ,
"์ด Promise๋ ์คํจํ ๊ฒ์ด๋ฉฐ, ์๋ฌ ๋ฉ์์ง๋ โฆ์ผ ๊ฒ์ด๋ค."
๋ฅผ ํํํ๋ค.
const fetchDataWithError = () => Promise.reject(new Error('Unauthorized'));
test('fetchDataWithError๊ฐ Unauthorized ์๋ฌ๋ก reject๋์ด์ผ ํ๋ค', async () => {
await expect(fetchDataWithError()).rejects.toThrow('Unauthorized');
});
์ด ๊ตฌ๋ฌธ์ ์๋์ ๋์ผํ ๋ก์ง์ด๋ค ๐
try {
await fetchDataWithError();
} catch (error) {
expect(error).toThrow('Unauthorized');
}
โ ์์ฝ
await expect(Promise).rejects.๋งค์ฒ() resolves / rejects๋ Promise์๋ง ์ฌ์ฉ ๊ฐ๋ฅํ๋ค.
expect(123).resolves.toBe(123) โawait๋ฅผ ๊ผญ ๋ถ์ฌ์ผ ํ๋ค.
await ์์ด ์์ฑํ๋ฉด ํ
์คํธ๊ฐ ๋จผ์ ๋๋๋ฒ๋ฆด ์ ์๋ค.not์ ๋ชจ๋ ๋งค์ฒ์์ ์ฌ์ฉ ๊ฐ๋ฅํ์ง๋ง,
resolves / rejects๋ ๋น๋๊ธฐ ๋งค์ฒ ์ ์ฉ Modifier๋ค.