Skip to content

Instantly share code, notes, and snippets.

@js2me
Created July 31, 2019 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save js2me/cd9c80991b19cab45be32bb28766f414 to your computer and use it in GitHub Desktop.
Save js2me/cd9c80991b19cab45be32bb28766f414 to your computer and use it in GitHub Desktop.
Mock console.warn console.log console.error
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