将jQuery加载到React应用的Mocha测试中 [英] Load jQuery into Mocha test for React App
问题描述
我已经创建了类似于此处概述的本教程的Mocha测试设置: https: //github.com/jesstelford/react-testing-mocha-jsdom .
I've created a Mocha test setup similar to this tutorial outlined here: https://github.com/jesstelford/react-testing-mocha-jsdom.
我想知道如何将jQuery加载到此结构中.我已经将它包含为require('jquery')
测试JS文件,但是当我调用$.ajax
时,它给出了一个错误,提示TypeError: Attempted to wrap undefined property ajax as function
.我怀疑这是因为Node没有在浏览器中运行我的JavaScript.但是,我尝试使用窗口环境 ,但仍然没有运气.
I'm wondering how I can load in jQuery into this structure. I've included it as require('jquery')
test JS file, but when I call $.ajax
, it gives an error saying TypeError: Attempted to wrap undefined property ajax as function
. I suspect that this is because Node is not running my JavaScript inside a browser. However, I've tried using a window environment, but still no luck.
我知道传统的方式是将jQuery包含在HTML标签中,但是由于我没有HTML文件,因此我不确定如何在此处执行此操作.
I know the traditional way is to include jQuery in HTML tags, but I'm not sure how to do that here, since I don't have an HTML file.
推荐答案
这是一种适用于我在mocha中某些jquery方法的模式,我不确定它是否适用于ajax,但可以尝试一下.让我知道.
This is a pattern that has worked for me for certain jquery methods in mocha, I'm not sure it'll work for ajax but give it a shot and let me know.
import jsdom from 'jsdom'
import _$ from 'jquery'
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>')
global.window = global.document.defaultView
const $ = _$(global.window)
这篇关于将jQuery加载到React应用的Mocha测试中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!