本文介绍了如何配置Jest使用的jsdom实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个问题在开玩笑的测试案例中要求systemjs时,抛出了无效的URL

最后的评论之一建议

通过在jsdom中设置引荐来源网址配置,使jsdom实例具有有效的位置/baseURI."

"manipulate the jsdom instance to have a valid location / baseURI by setting the referrer config in jsdom."

我想知道有没有办法做到这一点?我可以通过jest对象以某种方式访问​​jsdom实例吗?

I'm wondering is there way for me to do that? Can I access the jsdom instance somehow from the jest object?

推荐答案

在使用需要URL(location.href)的项目时,我遇到了类似的问题.您可以在配置中使用testURL配置jest.

I had a similar issue when using a project requiring a url (location.href). You can configure jest with a testURL in your configuration.

这是您可能会在package.json中放入的内容(如果这是配置jest的方式).

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文档

如果需要对jsdom进行更具体的更改,则可以自己安装jsdom并与jest分开导入和配置它.这是一个示例:

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

这篇关于如何配置Jest使用的jsdom实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 13:22