2017-03-02 61 views
0

我将Reactjs逐步集成到使用HTML5和jQuery构建的Web应用程序前端中。我的反应组件使用全局jQuery对象(用于AJAX和一些动画),当反应组件javascript被加载时可用。酶测试使用全局jQuery对象的Reactjs组件

现在,当我尝试mount()与酶测试该组件,它得到以下错误

ReferenceError: jQuery is not defined 

怎样使jQuery对象可用于安装的部件?

Testing a React component that uses jQuery & window object是0答案...

我愿意在必要时更新组件代码类似的问题。

任何帮助将不胜感激。

编辑

我的组件

import React from 'react'; 

    export default class MySimpleComponent extends React.Component { 

    constructor(props) { 
     super(props); 
    } 

    componentDidMount() { 
     var add_btn = this.refs.btn_add; 
     (function ($) { 
      $(add_btn).click(function (ev) { 
       ev.preventDefault(); 
       console.log('button was clicked'); 
      }); 
     })(jQuery); 
    } 

    render() { 
     return (
      <div className="wrap"> 
       <form action="/"> 
       <input type="text" name="myinput" value="" /> 
       <button className="button" ref="btn_add">New Record</button> 
       </form> 
      </div> 
     ); 
    } 
    } 
+0

您可以发布组件代码请 – spirift

+0

@spirift我已添加代码 – Ejaz

回答

1

奥凯的示例代码,所以你也许能jsdom做到这一点。你必须按照他们在自述文件中所说的设置一些全局变量。只需添加global.jQuery =() => {};

var jsdom = require('jsdom').jsdom; 

global.document = jsdom(''); 
global.jQuery =() => {}; 
global.window = document.defaultView; 
Object.keys(document.defaultView).forEach((property) => { 
    if (typeof global[property] === 'undefined') { 
    global[property] = document.defaultView[property]; 
    } 
}); 

global.navigator = { 
    userAgent: 'node.js' 
}; 

我还没有机会尝试以上。不过,我不会将此推荐为可持续解决方案。一个更好的方法是放弃jQuery。这里是你的组件重构没有它。

import React from 'react'; 

    export default class MySimpleComponent extends React.Component { 

    constructor(props) { 
     super(props); 
    } 

    clickHanlder(ev) { 
     ev.preventDefault(); 
     console.log('button was clicked'); 
    } 

    render() { 
     return (
      <div className="wrap"> 
       <form action="/"> 
       <input type="text" name="myinput" value="" /> 
       <button className="button" onClick={this.clickHanlder}>New Record</button> 
       </form> 
      </div> 
     ); 
    } 
    } 

正如你可以看到它没有那么不同。您可以将事件处理程序直接附加到元素上,对我来说,这使代码更易于阅读并查看操作的位置,可以这么说。

+0

感谢您的回答。我实际上修改了我的组件的一小部分,以使用本机事件处理,并消除了错误。我想我最终会从我的组件中删除所有jQuery代码,并试图合并其他一些动画元素.. CSS转换可能是。 – Ejaz

+0

查看[react velocity](https://github.com/twitter-fabric/velocity-react)或[react motion](https://github.com/chenglou/react-motion) – spirift