Mocking `document` in jest

后端 未结 8 1357
我在风中等你
我在风中等你 2020-11-29 04:12

I\'m trying to write tests for my web components projects in jest. I already use babel with es2015 preset. I\'m facing an issue while loading the js file. I have followed a

相关标签:
8条回答
  • 2020-11-29 04:17

    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"
        ],
    
    0 讨论(0)
  • 2020-11-29 04:23

    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.

    0 讨论(0)
  • 2020-11-29 04:26

    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', {});
    })
    
    0 讨论(0)
  • 2020-11-29 04:27

    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()
    });
    
    0 讨论(0)
  • 2020-11-29 04:29

    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
    };
    
    0 讨论(0)
  • 2020-11-29 04:29

    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

    0 讨论(0)
提交回复
热议问题