Skip to content

Instantly share code, notes, and snippets.

@natterstefan
Last active December 12, 2023 09:49
Show Gist options
  • Save natterstefan/8294b498afa35723ca92f3bf8451e533 to your computer and use it in GitHub Desktop.
Save natterstefan/8294b498afa35723ca92f3bf8451e533 to your computer and use it in GitHub Desktop.
Jest | Mock jsdom errors
import React, { FunctionComponent } from 'react'
import { mount } from 'enzyme'
import Compontent from '../'
describe('Component with Errors', () => {
beforeEach(() => {
jest.spyOn(console, 'error')
;(console as any).error.mockImplementation(() => null)
})
afterEach(() => {
;(console as any).error.mockRestore()
})
it('throws if view could not be found', () => {
expect(() => {
mount(<Component />)
}).toThrow()
})
})
const { configure } = require('enzyme')
const Adapter = require('enzyme-adapter-react-16')
configure({ adapter: new Adapter() })
/**
* jsdom reports errors in testing with
* `window._virtualConsole.emit("jsdomError", jsdomError);`. To be able to mock
* it we overwrite all jsdomError listeners.
*
* @example
* ```tsx
* beforeEach(() => {
* jest.spyOn(console, 'error')
* ;(console as any).error.mockImplementation(() => null)
* })
*
* afterEach(() => {
* ;(console as any).error.mockRestore()
* })
* ```
*
* Docs
* @see https://stackoverflow.com/a/48788756/1238150
*/
;(window as any)._virtualConsole.removeAllListeners('jsdomError')
;(window as any)._virtualConsole.addListener('jsdomError', error => {
console.error('nothing here', error)
})
// here's how the code we are going to mock looks like
// node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js
if (!handled) {
const errorString = shouldBeDisplayedAsError(error) ? `[${error.name}: ${error.message}]` : util.inspect(error);
const jsdomError = new Error(`Uncaught ${errorString}`);
jsdomError.detail = error;
jsdomError.type = "unhandled exception";
window._virtualConsole.emit("jsdomError", jsdomError);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment