Javascript 测试使用jQuery的React组件&;窗口对象
我的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
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.$
方面取得了成功。