【发布时间】: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