jquery doesn't work with jsdom/enzyme

后端 未结 3 1285
时光说笑
时光说笑 2021-01-12 17:00

I have a minimum test react app with following component:

import React from \'react\';
import $ from \'jquery\';

export default class App extends React.Comp         


        
相关标签:
3条回答
  • 2021-01-12 17:12

    I couldn't get Phuong Nguyen's answer to work. I did find the relevant page in the enzyme docs. I ended up with something like, based on the final example on that page:

    const div = global.document.createElement('div');
    global.document.body.appendChild(graphDiv);
    const wrapper = mount(<SomeComponent />, { attachTo: div });  // same as the other answer
    // clean up after ourselves
    wrapper.detach();
    global.document.body.removeChild(div);
    
    0 讨论(0)
  • 2021-01-12 17:13

    Finally found the issue:

    Enzyme mount(<SomeComponent />) by default will do full DOM rendering but not insert the rendered component into current document (JSDom). That's why jQuery cannot find any element in current document

    To do full DOM rendering AND attach to current document:

    mount(<SomeComponent />, { attachTo: document.getElementById('app') });
    

    Where app is empty div available when jsdom is setup:

    global.document = jsdom('<html><head></head><body><div id="app" /></body></html>');
    
    0 讨论(0)
  • 2021-01-12 17:27

    There needs to be some setup done before you could jsdom with jquery in node-env.

    Try this if it helps.

    Create a test helper file like this -

    test_helper.js

    import _$ from 'jquery';
    import jsdom from 'jsdom';
    import chai, { expect } from 'chai';
    import chaiJquery from 'chai-jquery';
    
    global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
    global.window = global.document.defaultView;
    global.navigator = global.window.navigator;
    const $ = _$(window);
    
    chaiJquery(chai, chai.util, $);
    
    export {expect};
    

    While running -

    mocha --require enzyme/withDom --compilers js:babel-core/register --require test/test_helper.js test/index.test.js
    

    or another way use jsdom-global without test_helper.js file.

    npm install --save-dev jsdom-global
    

    Then :

    import 'jsdom-global/register'; 
    
    //at the top of file , even  , before importing react
    
    0 讨论(0)
提交回复
热议问题