在Mocha Chai测试脚本中未定义$

时间:2019-12-16 12:30:33

标签: javascript jquery unit-testing mocha chai

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

  

npm测试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”),但是在运行此测试脚本时,我遇到了类似“ $未定义”的错误'

  

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函数进行单元测试

1 个答案:

答案 0 :(得分:0)

这可能是由于$冲突引起的

请点击here了解如何避免这种情况。

在多次加载jQuery文件时也会发生$冲突。您还可以检查一下吗?

相关问题