【问题标题】:$ is not defined in mocha chai test script$ 未在 mocha chai 测试脚本中定义
【发布时间】:2019-12-16 12:30:33
【问题描述】:

我正在尝试为 js 函数编写单元测试用例,它在 .js 文件中将其加载到 test.js 文件然后运行

npm test test.js

我的测试脚本包含

const app = require('../js/customJs/myjs.js');
var assert = require('chai').assert;
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
describe('Testing my test functions', function () {
     console.log("ready 2 test d dom");
     const dom = new JSDOM('<!DOCTYPE html><p id="myid"></div>');
     it('check the return value of helloworld module', function () {
         assert.equal(dashboard_tab.helloworld(),"hello");
     });
});

'myjs.js' 文件具有 helloworld 函数,该函数从 dom 元素获取值并调用 ajax 调用, 所以我正在尝试对返回值是否为“hello”进行单元测试('当然这个测试失败了,因为该函数不会返回 hello'),但是在运行这个测试脚本时我得到了错误,比如'$ is not defined '

myjs.js

var count = 0;
       function helloworld(){
          var id_Val = $("#myid").val();  //i was getting $ is not defined here when i run test.js
           $.ajax({
                url: "test/",
                data: { 'id': id_Val },
                dataType: 'json',
                   success: function (data) {
                    //some code
                  }
           });
       }

我试过了

global.$ = require('jquery')(window); // 现在,没有定义窗口

如何对包含 jquery ($) 的 js 函数进行单元测试

【问题讨论】:

    标签: javascript jquery unit-testing mocha.js chai


    【解决方案1】:

    这可能是$冲突造成的

    请点击here了解如何避免。

    $conflict 也会在你多次加载 jQuery 文件时发生。你能检查一下吗

    【讨论】:

    • 感谢 Ansar joseph,根据该链接,var $j = jQuery.noConflict();我必须将我的所有 jquery 从 '$' 别名为 '$j' ,这对于我的文件(包含 4000 行代码)是不可能的。
    • 你也可以试试这个 (function( $ ) { // 你的 jQuery 代码在这里,使用 $ })( $j );
    猜你喜欢
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多