gpt4 book ai didi

javascript - 将 jQuery 与 mocha-jsdom 一起使用时如何修复 "ReferenceError: $ is not defined"?

转载 作者:行者123 更新时间:2023-11-30 15:57:18 25 4
gpt4 key购买 nike

我在我的项目中设置 ES6 单元测试,但在使用库时遇到了一些问题。我想我会使用 jQuery 作为测试来尝试让它工作。没有图书馆,测试工作。

请注意,jQuery 已导入到我的 main.js 文件中,因此它在整个项目中都可用。

我的 JS 文件如下所示:

class Test {
constructor(options) {
this.init();
}

init() {
$('.test-div').addClass('test');
}

sayHello() {
return 'hello world!';
}
}

export default Test;

测试看起来像这样:

import jsdom from 'mocha-jsdom';
import chai from 'chai';
import Test from './test';

chai.should();

describe('Frequency', () => {

var $;
jsdom();

before(() => {
$ = require('jquery');
})

it('should output hello world', () => {
const test = new Test();
test.sayHello().should.equal('hello world!');
});

});

如果我删除 init() 函数,则测试有效。但是,before 函数似乎没有为测试导入 jQuery。我在控制台收到的错误如下:

ReferenceError: $ is not defined
at Frequency.init

最佳答案

我复制了你的代码并通过修改 before Hook 使其工作:

before(() => {
$ = require('jquery');
global.$ = $;
});

如果您阅读 mocha-jsdom在 的文档中,您会看到它放入了全局空间符号,如 windowdocument。当您加载 jquery 时,它会找到 window 并将自己添加为 window.$。在浏览器中,这使$ 在全局空间中可见,因为window 全局空间。然而,在 Node 中,全局空间是 global,因此您必须自己将 $ 放入其中。

关于javascript - 将 jQuery 与 mocha-jsdom 一起使用时如何修复 "ReferenceError: $ is not defined"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38309405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com