Resolving "ReferenceError: document is not defined" in WebStorm using Jest

This is an error that I've seen plague several projects when using the Jest Test runner in WebStorm. I have found two working resolutions to this. You can either.

  1. Add this block of code below the imports in the test file that is having the error.
    import jsdom from 'jsdom';
    const doc = jsdom.jsdom('<!doctype html>test');
    global.document = doc;
    global.window = doc.defaultView;
    
  2. Alternatively put "--env=jsdom" in the "Jest options" field in the specific runners configuration. Should look something like this. jsdom

Either way the error should now be gone when you run your tests.

Copyright © 2020 | Ben Hutton