简体   繁体   English

使用 Mocha 使用 Typescript 对 Jquery 进行单元测试时,如何修复“$ 未定义”错误?

[英]How to fix “$ is not defined” error when unit testing Jquery with Typescript using Mocha?

I am writing Mocha unit tests for Typescript code containing Jquery .我正在为包含Jquery 的Typescript代码编写Mocha单元测试。 I'm using jsdom for getting the document object.我正在使用jsdom来获取文档对象。 When I compile my TS code to JS and run the tests, it throws an error [ReferenceError: $ is not defined] .当我将 TS 代码编译为 JS 并运行测试时,它会引发错误[ReferenceError: $ is not defined]

My Typescript code is here我的打字稿代码在这里

export function hello(element) : void {
    $(element).toggleClass('abc');
};

My unit test code is as follows:我的单元测试代码如下:

import {hello} from '../src/dummy';

var expect = require('chai').expect;
var jsdom = require('jsdom');
var document = jsdom.jsdom();
var window = document.defaultView;

var $ = require('jquery')(window);

describe('TEST NAME', () => {

    it('should run', (done) => {
        hello($('div'));
        done();
    });
});

When I run Mocha test it shows当我运行 Mocha 测试时,它显示

    <failure message="$ is not defined"><![CDATA[ReferenceError: $ is not defined ...
]]></failure>

Also tried using global.$ = require("jquery");也尝试使用global.$ = require("jquery"); but does not work.但不起作用。

jQuery has to be available globally because your script gets it from the global space. jQuery 必须全局可用,因为您的脚本从全局空间获取它。 If I modify your code so that var $ = require('jquery')(window);如果我修改您的代码,以便var $ = require('jquery')(window); is replaced by:被替换为:

global.$ = require('jquery')(window);

then it works.那么它的工作原理。 Note the two calls: 1st to require jquery , then to build it by passing window .注意两个调用:第一个需要jquery ,然后通过传递window来构建它。 You could alternatively do:你也可以这样做:

global.window = window
global.$ = require('jquery');

If window is available globally, then there is no need to perform the double call as in the first snippet: jQuery just uses the globally available window .如果window全局可用,则不需要像第一个片段中那样执行双重调用:jQuery 只使用全局可用的window

You probably also want to define global.jQuery since some scripts count on its presence.您可能还想定义global.jQuery因为某些脚本依赖于它的存在。

Here is a full example of a test file that runs:这是运行的测试文件的完整示例:

/// <reference path="../typings/mocha/mocha.d.ts" />
/// <reference path="../typings/chai/chai.d.ts" />
/// <reference path="../typings/jsdom/jsdom.d.ts" />
/// <reference path="./global.d.ts" />

import {hello} from './dummy';

import chai = require('chai');
var expect = chai.expect;
import jsdom = require('jsdom');
var document = jsdom.jsdom("");
var window = document.defaultView;

global.window = window
global.$ = require('jquery');

describe('TEST NAME', () => {

    it('should run', (done) => {
        hello($('div'));
        done();
    });
});

The typings files are obtained the usual way using tsd .typings文件获得使用通常方式tsd The file ./global.d.ts fixes the issue you may get with setting new values on global .文件./global.d.ts修复了在global上设置新值时可能遇到的问题。 It contains:它包含:

declare namespace NodeJS {
    interface Global {
      window: any;
      $: any;
    }
}

dummy.js was also modified like this: dummy.js也做了如下修改:

declare var $: any;

export function hello(element) : void {
    $(element).toggleClass('abc');
};

You need to include jsdom and jQuery in Node first:你需要先在 Node 中包含 jsdom 和 jQuery:

 npm install jsdom --save-dev npm install jquery --save-dev

and then add this lines into your .js file where you are using jQuery然后将此行添加到您使用 jQuery 的 .js 文件中

 const jsdom = require("jsdom"); const { JSDOM } = jsdom; const { window } = new JSDOM(`...`); var jQuery = require('jquery')(window); var example = (function($) { .....your jQuery code.... })(jQuery); module.exports = example;

I found this question in 2020 and Louis got me pointing in the right direction.我在 2020 年发现了这个问题,路易斯让我指出了正确的方向。 However, I found jsdom-global an easier alternative way of getting document working in Mocha.但是,我发现jsdom-global是一种在 Mocha 中获取文档的更简单的替代方法。 I installed jsdom-global following the instructions at jsdom-globaljsdom-global的说明安装了jsdom-global

I used these lines to get jQuery and $ working as expected:我使用这些行让 jQuery 和 $ 按预期工作:

require('jsdom-global')();
global.window = window;
global.$ = require('jquery');
global.jQuery = $;

Then this test passed with flying colours:然后这个测试以优异的成绩通过了:

const assert = require("chai").assert;
function test(){
    return "test";
}
describe('Setting up global constants...', function () {
    describe('Libraries...', function () {
        it('jQuery and $ are present', () => {
            assert(jQuery !== undefined);
            assert($ !== undefined);
            assert($ === jQuery);
            assert($.isFunction(test));
        });
    });
});

If you can't or don't want to alter the global namespace type definition, you can still include jQuery, as following:如果您不能或不想更改全局命名空间类型定义,您仍然可以包含 jQuery,如下所示:

const globalAny:any = global;
const $ = globalAny.$ = require('jquery')(window);

The full initialization of jQuery then becomes: jQuery 的完整初始化然后变成:

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = (new JSDOM());
const globalAny:any = global;
const $ = globalAny.$ = require('jquery')(window);

如上所述,您应该正确导入 jQuery: import $ = require('jquery');

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

相关问题 jQuery没有定义使用mocha来测试wordpress javascript - jQuery not defined using mocha for testing wordpress javascript 如何修复jquery库中的&#39;jQuery is not defined&#39;错误? - how to fix 'jQuery is not defined' error in jquery library? 错误:“ jQuery需要带有文档的窗口”以及Mocha和Typescript? - Error: “jQuery requires a window with a document” with mocha and typescript? 如何修复“未定义 jQuery”错误? - How do I fix "jQuery is not defined" error? 尝试使用Chai&Mocha测试旧版jQuery插件时未定义jQuery - jQuery is not defined when trying to test legacy jQuery plugin using Chai & Mocha 当我使用插件 Autoptimize Js 时,如何修复“未定义 jQuery”? [等候接听] - How can fix ' jQuery is not defined ' when i using plugin Autoptimize Js? [on hold] 使用jQuery运行命令行Mocha时出错 - Error running command line Mocha using jQuery 为什么我在单元测试中收到 `ReferenceError: jQuery is not defined` - Why i get `ReferenceError: jQuery is not defined` on unit testing 使用jQuery对DOM中的文本操作进行单元测试 - Unit testing text manipulation in the DOM using jQuery 使用jQuery创建DOM结构进行单元测试 - Creating DOM structure using jQuery for unit testing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM