Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 测试使用jQuery的React组件&;窗口对象_Javascript_Jquery_Unit Testing_Reactjs_Jestjs - Fatal编程技术网

Javascript 测试使用jQuery的React组件&;窗口对象

Javascript 测试使用jQuery的React组件&;窗口对象,javascript,jquery,unit-testing,reactjs,jestjs,Javascript,Jquery,Unit Testing,Reactjs,Jestjs,我的React组件必须响应resize事件,我正在使用jQuery,即: //... componentDidMount: function() { $(window).on("resize", function); } //.. 但是,这会导致我的Jest测试出现问题,具体来说: - TypeError: Cannot read property 'on' of undefined at RadiumEnhancer.React.createClass.componentDidM

我的React组件必须响应
resize
事件,我正在使用jQuery,即:

//...
componentDidMount: function() {
  $(window).on("resize", function);
}
//..
但是,这会导致我的Jest测试出现问题,具体来说:

- TypeError: Cannot read property 'on' of undefined
    at RadiumEnhancer.React.createClass.componentDidMount (bundles/Opportunities/OpportunityPartial.jsx:21:14)
当单步执行测试时,窗口似乎是在jest测试中定义的,但是
$(窗口)
似乎没有返回任何内容

我的印象是Jest将检查所需模块(jQuery)的API以构建其模拟,但如果我正确理解了问题,那么这似乎不会发生


我可以通过不模仿jQuery来解决这个问题,但显然这并不完全可取。

下面是使用
jestjs
enzyme
的单元测试解决方案:

index.tsx

import React,{Component}来自'React';
从“jquery”导入美元;
类SomeComponent扩展组件{
componentDidMount(){
$(window).on('resize',this.resizeEventHandler);
}
resizeEventHandler(){
log('resizeeventhandler');
}
render(){
返回一些组件;
}
}
导出默认组件;
index.spec.tsx

从“React”导入React;
从“/”导入某些组件;
从“酶”导入{shall};
从“jquery”导入美元;
jest.mock('jquery',()=>{
常数m$={
on:jest.fn(),
};
return jest.fn(()=>m$);
});
描述('36082197',()=>{
之后(()=>{
开玩笑。恢复记忆();
jest.resetAllMocks();
});
它('应该通过',()=>{
constlogspy=jest.spyOn(控制台,'log');
const eventHandlerMap={};

($().on as jest.MockedFunction

我不确定这是否正确,但在您的例子中,我在
之前(()=>{window.jQuery=require('jQuery');});
window.$
方面取得了成功。