Mocking `document` in jest

后端 未结 8 1358
我在风中等你
我在风中等你 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('<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

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

    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;
        });
    
    0 讨论(0)
提交回复
热议问题