Created
March 13, 2024 15:46
-
-
Save groupsky/2c089a5db63eefcb7db12611a0c00522 to your computer and use it in GitHub Desktop.
Paranoid jest console setup
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 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