Last active
August 22, 2024 08:37
-
-
Save natterstefan/8294b498afa35723ca92f3bf8451e533 to your computer and use it in GitHub Desktop.
Jest | Mock jsdom errors
This file contains hidden or 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
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() | |
}) | |
}) |
This file contains hidden or 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 { 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) | |
}) |
This file contains hidden or 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
// 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