How can I configure the jsdom instance used by jest?

前端 未结 4 1155
清歌不尽
清歌不尽 2021-02-13 23:07

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 instan

4条回答
  •  独厮守ぢ
    2021-02-13 23:38

    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 = '';
    
    // 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
    

提交回复
热议问题