diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c44b8ae306d..69fca9aaa49e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ * `[jest-util]` Fix `runOnlyPendingTimers` for `setTimeout` inside `setImmediate` ([#4608](https://github.com/facebook/jest/pull/4608)) * `[jest-message-util]` Always remove node internals from stacktraces ([#4695](https://github.com/facebook/jest/pull/4695)) * `[jest-resolve]` changes method of determining builtin modules to include missing builtins ([#4740](https://github.com/facebook/jest/pull/4740)) +* `[pretty-format]` Prevent error in pretty-format for window in jsdom test env ([#4750](https://github.com/facebook/jest/pull/4750)) ### Features * `[jest-environment-*]` [**BREAKING**] Add Async Test Environment APIs, dispose is now teardown ([#4506](https://github.com/facebook/jest/pull/4506)) diff --git a/packages/pretty-format/src/__tests__/dom_element.test.js b/packages/pretty-format/src/__tests__/dom_element.test.js index 14a00dcb30d7..2e863e0fd715 100644 --- a/packages/pretty-format/src/__tests__/dom_element.test.js +++ b/packages/pretty-format/src/__tests__/dom_element.test.js @@ -18,6 +18,13 @@ const toPrettyPrintTo = require('./expect_util').getPrettyPrint([DOMElement]); const expect: any = global.expect; expect.extend({toPrettyPrintTo}); +describe('pretty-format', () => { + // Test is not related to plugin but is related to jsdom testing environment. + it('prints global window as constructor name alone', () => { + expect(prettyFormat(window)).toEqual('[Window]'); + }); +}); + describe('DOMElement Plugin', () => { it('supports a single HTML element', () => { expect(document.createElement('div')).toPrettyPrintTo('
'); diff --git a/packages/pretty-format/src/index.js b/packages/pretty-format/src/index.js index 35a591c90da8..c1df9ac4ebcd 100644 --- a/packages/pretty-format/src/index.js +++ b/packages/pretty-format/src/index.js @@ -41,6 +41,10 @@ const errorToString = Error.prototype.toString; const regExpToString = RegExp.prototype.toString; const symbolToString = Symbol.prototype.toString; +// Is val is equal to global window object? Works even if it does not exist :) +/* global window */ +const isWindow = val => typeof window !== 'undefined' && val === window; + const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; const NEWLINE_REGEXP = /\n/gi; @@ -224,7 +228,9 @@ function printComplexValue( '}'; } - return hitMaxDepth + // Avoid failure to serialize global window object in jsdom test environment. + // For example, not even relevant if window is prop of React element. + return hitMaxDepth || isWindow(val) ? '[' + (val.constructor ? val.constructor.name : 'Object') + ']' : (min ? '' : (val.constructor ? val.constructor.name : 'Object') + ' ') + '{' +