Created
July 31, 2019 10:18
-
-
Save js2me/cd9c80991b19cab45be32bb28766f414 to your computer and use it in GitHub Desktop.
Mock console.warn console.log console.error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mockedMethods = ['log', 'warn', 'error'] | |
export const { originalConsoleFuncs, consoleMessages } = mockedMethods.reduce( | |
(acc: any, method: any) => { | |
acc.originalConsoleFuncs[method] = console[method].bind(console) | |
acc.consoleMessages[method] = [] | |
return acc | |
}, | |
{ | |
consoleMessages: {}, | |
originalConsoleFuncs: {} | |
} | |
) | |
export const clearConsole = () => | |
mockedMethods.forEach(method => { | |
consoleMessages[method] = [] | |
}) | |
export const mockConsole = (callOriginals?: boolean) => { | |
const createMockConsoleFunc = (method: any) => { | |
console[method] = (...args: any[]) => { | |
consoleMessages[method].push(args) | |
if (callOriginals) return originalConsoleFuncs[method](...args) | |
} | |
} | |
const deleteMockConsoleFunc = (method: any) => { | |
console[method] = originalConsoleFuncs[method] | |
consoleMessages[method] = [] | |
} | |
beforeEach(() => { | |
mockedMethods.forEach((method: any) => { | |
createMockConsoleFunc(method) | |
}) | |
}) | |
afterEach(() => { | |
mockedMethods.forEach((method: any) => { | |
deleteMockConsoleFunc(method) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment