Skip to content

Instantly share code, notes, and snippets.

@groupsky
Created March 13, 2024 15:46
Show Gist options
  • Save groupsky/2c089a5db63eefcb7db12611a0c00522 to your computer and use it in GitHub Desktop.
Save groupsky/2c089a5db63eefcb7db12611a0c00522 to your computer and use it in GitHub Desktop.
Paranoid jest console setup
const isPromise = (candidate) => candidate && typeof candidate?.then === 'function'
beforeEach(() => {
jest.spyOn(console, 'debug')
jest.spyOn(console, 'log')
jest.spyOn(console, 'warn')
jest.spyOn(console, 'error')
})
afterEach(() => {
expect(console.debug).not.toHaveBeenCalled()
expect(console.log).not.toHaveBeenCalled()
expect(console.warn).not.toHaveBeenCalled()
expect(console.error).not.toHaveBeenCalled()
})
/**
* Wraps the callback in a test that expects the given logging to occur
* @param {'debug'|'log'|'warn'|'error'} method - The log method to expect
* @param {Function} callback - The test to run
* @returns {void|Promise<void>}
*/
const withExpectedLogging = (method, callback) => {
const returnedValue = console[method].withImplementation(() => {}, callback)
if (isPromise(returnedValue)) {
return returnedValue.then(() => {
console[method].mockClear()
})
} else {
console[method].mockClear()
}
}
test('Fails on unexpected log', () => {
console.log('unexpected')
})
test('Passes on expected log', () => {
withExpectedLogging('log', () => {
console.log('expected')
expect(console.log).toHaveBeenCalledWith('expected')
})
})
test('Fails on unexpected log after expected log', () => {
withExpectedLogging('log', () => {
console.log('expected')
})
console.log('unexpected')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment