简体   繁体   English

尝试使用Chai&Mocha测试旧版jQuery插件时未定义jQuery

[英]jQuery is not defined when trying to test legacy jQuery plugin using Chai & Mocha

I'm trying to write a unit test for old jQuery plugin. 我正在尝试为旧的jQuery插件编写单元测试。 I am kind of new in modern Javascript environment. 我是现代Javascript环境中的新手。 I have tried creating unit test for React that uses browserify for deploying in production. 我曾尝试为React创建单元测试,该单元测试使用browserify在生产中进行部署。

The legacy jQuery plugin file is like below 旧版jQuery插件文件如下所示

(function($) {
    $.fn.myLegacyPlugin = function() {
        alert('Hello World!');
    };
})(jQuery);

This file will be uploaded to S3 and accessed via CDN. 该文件将被上传到S3并通过CDN访问。 The jQuery will be included in normal browser head tag. jQuery将包含在常规浏览器的head标签中。

The test file is like below. 测试文件如下。

let expect = require('chai').expect;
let path = require('path');
let $ = require('jquery');

require('../src/plugin.js');

describe('plugin', () => {
    it('should return okay', () => {
        expect(true).to.be.true; //TODO
    });
});

The problem is that when I tried executing the test, the runner displays jQuery is not defined . 问题是,当我尝试执行测试时,运行器显示jQuery is not defined Without modifying the legacy jQuery plugin, how do I test the plugin? 在不修改旧版jQuery插件的情况下,如何测试该插件?

The code is here https://github.com/petrabarus/js-test-jquery-legacy 代码在这里https://github.com/petrabarus/js-test-jquery-legacy

After trying few possibilities, instead of using module import, I can just use read file and evaluate the script content. 在尝试了几种可能性之后,无需使用模块导入,而是可以使用读取文件并评估脚本内容。

Only change 只有改变

require('../src/plugin.js');

to this 对此

eval(fs.readFileSync(path.join(__dirname, '../src') + '/plugin.js', 'utf8'));

This way I don't have to modify the legacy file. 这样,我不必修改旧文件。

It might be that you are requiring jquery as "$" and passing it to plugin as "jQuery". 可能是您需要将jQuery作为“ $”并将其作为“ jQuery”传递给插件。 Although jquery should be defined with both names, regardless. 尽管jquery应该同时使用两个名称定义。 Could you try requiring jquery like so: 您可以尝试要求jquery这样吗:

let jQuery= require('jquery');

Answer 2: actually, if your code (plugin) depends on jquery, your plugin.js should require jquery before loading.. 答案2:实际上,如果您的代码(插件)取决于jquery,则plugin.js在加载之前应要求使用jquery。

so change plugin.js to 因此将plugin.js更改为

let $ = require('jquery');
// rest of plugin code...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM