I've come up against this issue Invalid URL is thrown when requiring systemjs in jest test cases
One of the last comments suggests
"manipulate the jsdom instance to have a valid location / baseURI by setting the referrer config in jsdom."
I'm wondering is there way for me to do that? Can I access the jsdom
instance somehow from the jest
object?
To set up a JSDOM environment within Jest, start by creating a new Jest configuration file called jest. config. js . In this file, export an object whose testEnvironment property's value is "jsdom" .
Jest actually ships with jsdom and the environment already configured. You can override it with the testEnvironment setting. If you need to set up more aspects of the environment though, you can use the setupTestFrameworkScriptFile setting to point to a file that executes before all of your tests run.
jsdom is a pure JavaScript implementation of the DOM and browser APIs that runs in node. If you're not using Jest and you would like to run your tests in Node, then you must install jsdom yourself. There's also a package called global-jsdom which can be used to setup the global environment to simulate the browser APIs.
Jest uses node as test environment by default. In order to tell Jest to use a different environment we will either have to set a CLI attribute, define it in "package. json" or add a property to your Jest config file.
I had a similar issue when using a project requiring a url (location.href). You can configure jest with a testURL in your configuration.
Here is what you might put in your package.json (if that is how you configure jest).
"jest": {
...other config,
"testURL": "http://localhost:8080/Dashboard/index.html"
}
testURL Doc
If you need more specific changes to jsdom you can install jsdom yourself and import and configure it separately from jest. Here is an example:
test.js
'use strict';
import setup from './setup';
import React from 'react';
import { mount } from 'enzyme';
import Reportlet from '../components/Reportlet.jsx';
it('Reportlet Renders', () => {
...some test stuff
});
setup.js
import jsdom from 'jsdom';
const DEFAULT_HTML = '<html><body></body></html>';
// Define some variables to make it look like we're a browser
// First, use JSDOM's fake DOM as the document
global.document = jsdom.jsdom(DEFAULT_HTML);
// Set up a mock window
global.window = document.defaultView;
global.window.location = "https://www.bobsaget.com/"
// ...Do extra loading of things like localStorage that are not supported by jsdom
I just went down this road and found out that as of Jest 21.2.1, the official way is to fork your own JSDom environment.
This is a bit painful to set up but allows in-depth customization.
References:
Sample environment: https://github.com/mes/jest-environment-jsdom-external-scripts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With