๊ธฐ๋ฅ ์ ์์ฒญํ๊ฑฐ๋ ๋ฒ๊ทธ ๋ฅผ ๋ณด๊ณ ํ์๊ฒ ์ต๋๊น?
ํน์ง
ํ์ฌ ํ๋์ ๋ฌด์์
๋๊น?
BufferedConsole
๋ก ์ธํด console.error
, console.log
, console.warn
๋ฐ console.info
๋ฅผ ๋ฎ์ด์ธ ์ ์์ต๋๋ค.
์ฌ์ฉ ์ฌ๋ก: console.error
๋ฐ console.warn
์์ ์ค๋ฅ๊ฐ ๋ฐ์ํ๊ณ ํ
์คํธ์ ์คํจํ๋๋ก ํ๊ณ ์ถ์ต๋๋ค.
ํ์ฌ ๋์์ด ๋ฒ๊ทธ์ธ ๊ฒฝ์ฐ ์ฌํํ๋ ๋จ๊ณ์ https://repl.it/languages/jest ๋ฅผ ํตํด repl.it ๋ฐ๋ชจ๋ฅผ ์ ๊ณตํ๊ฑฐ๋ GitHub์์ yarn install
๋ฐ yarn test
ํ ์ ์๋ ์ต์ ์ ์ฅ์๋ฅผ ์ ๊ณตํ์ธ์.
์์๋๋ ๋์์ ๋ฌด์์
๋๊น?
console.error = (message) => { throw new Error(message); };
(์ ์ญ์ ์ผ๋ก, ํ
์คํธ์์ ๋๋ setupFiles/setupFramework์์)๋ฅผ ์ถ๊ฐํ๋ฉด ํ
์คํธ์์ console.error
๊ฐ ํธ์ถ๋ ๋๋ง๋ค ์ค๋ฅ๊ฐ ๋ฐ์ํ๊ณ ํ
์คํธ์ ์คํจํ ๊ฒ์ผ๋ก ์์ํฉ๋๋ค.
์ค์ ๋ก๋ ์๋ฌด ์ผ๋ ์ผ์ด๋์ง ์์ต๋๋ค.
์ ํํ Jest ๊ตฌ์ฑ์ ์ ๊ณตํ๊ณ Jest, ๋ ธ๋, yarn/npm ๋ฒ์ ๋ฐ ์ด์ ์ฒด์ ๋ฅผ ์ธ๊ธํ์ญ์์ค.
ํด๋น ์์
์กฐ๋กฑ ํจ์ jest.fn()
์ฌ์ฉ:
console.warn = jest.fn(warn => {
throw new Error(warn);
});
@thymikee ์ ์ญ ์ค์ ํ์ผ์ ์ฌ์ฉํ์ฌ ์์๋๋ก ์๋ํ์ง ์์ต๋๋ค.
"setupTestFrameworkScriptFile": "<rootDir>/tools/jest/setup-framework.js"
beforeEach(() => {
console.error = jest.fn((error) => {
throw new Error(error);
});
});
ํ ์คํธ ์ค:
const somePromiseThatLogsConsoleError = () => {
return new Promise((resolve, reject) => {
console.error('foobar');
resolve();
});
});
it('test that has console.error', () => {
return somePromiseThatLogsConsoleError().then(() => {
expect(false).toBeTrue();
});
});
๋ฐฉ๊ธ ์๋ํ๊ณ ์๋ํ์ต๋๋ค.
// test file
test('lol', () => {
return new Promise((resolve) => {
console.log('lol');
resolve();
});
});
// setup file
global.console.log = () => {
throw new Error('hey!');
};
๊ฒฐ๊ณผ:
__tests__/test-test.js
โ lol (3ms)
โ lol
hey!
at CustomConsole.Object.<anonymous>.global.console.log (setup.js:2:9)
at resolve (__tests__/test-test.js:3:13)
at Object.<anonymous>.test (__tests__/test-test.js:2:10)
at process._tickCallback (internal/process/next_tick.js:109:7)
Test Summary
โบ Ran all tests.
โบ 1 test failed, 0 tests passed (1 total in 1 test suite, run time 0.661s)
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
์กฐ๋กฑ ํจ์
jest.fn()
์ฌ์ฉ: