Mocking `document` in jest

后端 未结 8 1388
我在风中等你
我在风中等你 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:29

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


    • super-project
      • config
        • __mocks__
          • 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('
    '); });

    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

提交回复
热议问题