From 67f53de6f24a928de65709a0496983b559ae96c4 Mon Sep 17 00:00:00 2001 From: "Kent C. Dodds" Date: Thu, 28 Sep 2017 16:20:27 -0600 Subject: [PATCH] fix(ssr): add type check for window (#205) Also add tests to avoid breaking SSR in the future --- other/ssr/__tests__/index.js | 20 ++++++++++++++++++++ other/ssr/jest.config.js | 9 +++++++++ src/downshift.js | 5 ++++- 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 other/ssr/__tests__/index.js create mode 100644 other/ssr/jest.config.js diff --git a/other/ssr/__tests__/index.js b/other/ssr/__tests__/index.js new file mode 100644 index 000000000..b345f6026 --- /dev/null +++ b/other/ssr/__tests__/index.js @@ -0,0 +1,20 @@ +import React from 'react' +import ReactDOMServer from 'react-dom/server' +import Downshift from '../../../src' + +test('does not throw an error when server rendering', () => { + expect(() => { + ReactDOMServer.renderToString( + + {({getInputProps, getLabelProps}) => ( +
+
+ )} +
+ ) + }).not.toThrow() +}) + +/* eslint jsx-a11y/label-has-for:0 */ diff --git a/other/ssr/jest.config.js b/other/ssr/jest.config.js new file mode 100644 index 000000000..17153eeb1 --- /dev/null +++ b/other/ssr/jest.config.js @@ -0,0 +1,9 @@ +// This is separate because the test environment is set via the config +// and we want most of our tests to run with jsdom, but we still want +// to make sure that the server rendering use case continues to work. +const jestConfig = require('kcd-scripts/config').jest + +module.exports = Object.assign(jestConfig, { + roots: ['.'], + testEnvironment: 'node', +}) diff --git a/src/downshift.js b/src/downshift.js index 301bb400c..f54ac97a2 100644 --- a/src/downshift.js +++ b/src/downshift.js @@ -63,7 +63,10 @@ class Downshift extends Component { onStateChange: () => {}, onUserAction: () => {}, onChange: () => {}, - environment: window, + environment: + typeof window === 'undefined' /* istanbul ignore next (ssr) */ + ? {} + : window, } // this is an experimental feature