开玩笑的“文件”

我正在尝试用开玩笑的方式为我的 web 组件项目编写测试。我已经使用巴别塔与 es2015预设。我在加载 js 文件时遇到了一个问题。我跟踪了一段代码,其中 document对象有一个 currentScript对象。但是在测试环境中,它是 null。所以我也想嘲笑一下。但是 jest.fn()在这方面并没有真正的帮助。我该如何处理这个问题?

玩笑开不起来的代码。

var currentScriptElement = document._currentScript || document.currentScript;
var importDoc = currentScriptElement.ownerDocument;

我写的测试用例

import * as Component from './sample-component.js';


describe('component test', function() {
it('check instance', function() {
console.log(Component);
expect(Component).toBeDefined();
});
});

下面是 jest 抛出的错误

Test suite failed to run


TypeError: Cannot read property 'ownerDocument' of null


at src/components/sample-component/sample-component.js:4:39

更新: 根据 Andreas Köberle 的建议,我添加了一些全局变量,并试图模仿如下

__DEV__.document.currentScript = document._currentScript = {
ownerDocument: ''
};
__DEV__.window = {
document: __DEV__.document
}
__DEV__.document.registerElement = jest.fn();


import * as Component from './arc-sample-component.js';


describe('component test', function() {
it('check instance', function() {
console.log(Component);
expect(Component).toBeDefined();
});
});

但是不走运

更新: 我在没有 __dev__的情况下尝试了上面的代码。

123833 次浏览

I have resolved this using setUpFiles property in jest. This will execute after jsdom and before each test which is perfect for me.

Set setupFiles, in Jest config, e.g.:

"setupFiles": ["<rootDir>/browserMock.js"]




// browserMock.js
Object.defineProperty(document, 'currentScript', {
value: document.createElement('script'),
});

Ideal situation would be loading webcomponents.js to polyfill the jsdom.

I could resolve this same issue using global scope module on nodejs, setting document with mock of document, in my case, getElementsByClassName:

// My simple mock file
export default {
getElementsByClassName: () => {
return [{
className: 'welcome'
}]
}
};


// Your test file
import document from './name.component.mock.js';
global.document = {
getElementsByClassName: document.getElementsByClassName
};

If like me you're looking to mock document to undefined (e.g. for server side / client side tests) I was able to use object.defineProperty inside my test suites without having to use setupFiles

Example:

beforeAll(() => {
Object.defineProperty(global, 'document', {});
})

If you need to define test values for properties, there is a slightly more granular approach. Each property needs to be defined individually, and it's also necessary to make the properties writeable:

Object.defineProperty(window.document, 'URL', {
writable: true,
value: 'someurl'
});

See: https://github.com/facebook/jest/issues/890

This worked for me using Jest 21.2.1 and Node v8.11.1

Similar to what others have said, but instead of trying to mock the DOM yourself, just use JSDOM:

// __mocks__/client.js


import { JSDOM } from "jsdom"
const dom = new JSDOM()
global.document = dom.window.document
global.window = dom.window

Then in your jest config:

    "setupFiles": [
"./__mocks__/client.js"
],

I have been struggling with mocking document for a project I am on. I am calling document.querySelector() inside a React component and need to make sure it is working right. Ultimately this is what worked for me:

it('should test something', () => {
const spyFunc = jest.fn();
Object.defineProperty(global.document, 'querySelector', { value: spyFunc });
<run some test>
expect(spyFunc).toHaveBeenCalled()
});

Hope this helps

const wrapper = document.createElement('div');
const render = shallow(<MockComponent{...props} />);
document.getElementById = jest.fn((id) => {
wrapper.innerHTML = render.find(`#${id}`).html();
return wrapper;
});

This is the structure in my project named super-project inside the folder super-project:


  • super-project
    • config
        • dom.js
    • src
      • user.js
    • tests
      • user.test.js
    • jest.config.js
    • package.json

You need to setup Jest to use a mock in your tests:

dom.js:

import { JSDOM } from "jsdom"
const dom = new JSDOM()
global.document = dom.window.document
global.window = dom.window

user.js:

export function create() {
return document.createElement('table');
}

user.test.js:

import { create } from "../src/user";


test('create table', () => {
expect(create().outerHTML).toBe('<table></table>');
});

jest.config.js:

module.exports = {
setupFiles: ["./config/__mocks__/dom.js"],
};

References:

You need to create a manual mock:
https://jestjs.io/docs/en/manual-mocks.html

Manipulating DOM object:
https://jestjs.io/docs/en/tutorial-jquery

Jest Configuration:
https://jestjs.io/docs/en/configuration

I found another solution. Let's say inside of your component you want to get a reference to an element in the DOM by className (document.getElementsByClassName). You could do the following:

let wrapper
beforeEach(() => {
wrapper = mount(<YourComponent/>)
jest.spyOn(document, 'getElementsByClassName').mockImplementation(() =>
[wrapper.find('.some-class').getDOMNode()]
)
})

This way you are manually setting the return value of getElementsByClassName equal to the reference of .some-class. It might be necessary to rerender the component by calling wrapper.setProps({}).

Hope this helps some of you!