使用 qunit 测试我的代码时出错
Error on testing my code with qunit
这是应用程序的代码。所有其余函数都是从init()
调用的。
如何开始用 qunit 测试代码,因为如果我直接在 tests.js 文件中调用函数,它说"ReferenceError: init is not defined
"。
var SOUND;
(function ($, undefined) {
// some code here
// and has variables and functions defined which get called inside this and are all interdependent.
init = function () {
}
})(jQuery);
您的问题是您在 IFFE 中声明了您的init
函数,并且该函数范围之外的任何内容都无法访问它。您可以使用非常简单的"模块"模式来解决此问题,该模式从 IFFE 返回 init 方法并将其分配给变量。
.JS
// "namespace" for your application.
// Whatever your IFFE returns is assigned to the App variable
// this allows other scripts to use your application code
var App = (function ($, undefined) {
// some code here
// and has variables and functions defined which get called inside this and are all interdependent.
// example of a function inside your "application" js
var printTitle = function () {
var title = document.title;
console.log(title);
}
var init = function () {
printTitle();
}
// expose internal methods by returning them.
// you should probably be exposing more than your init method
// so you can unit test your code
return {
init: init
}
})(jQuery);
// since we've returned the init function from within our iffe
// and that function is assigned to the App variable
// we are able to call App.init here
App.init(); // logs title
JSFiddle
我发现以下文章对进行 js 测试很有帮助:
- 编写可测试的前端Javascript第1部分 - 反模式及其修复
- 编写可测试的 Javascript
- 基本 JS 设计模式
相关文章:
- 我在代码点火器中出错
- 将javascript代码转换为jquery代码时出错
- 我的Javascript代码出错
- 在Tomcat中运行Javascript代码时出错
- 不允许的关键字符.通过 Codeigniter 中的 jQuery 在帧中加载嵌入代码时出错
- 运行Javascript继承代码时出错
- 将js代码转换为jQueryMobile时出错
- 将Flask中的变量显示为javascript代码时出错
- 代码在shell中运行,但提供'可以't查找变量'从文件运行时出错
- 我的代码出错
- 如何将鼠标悬停在链接上时显示demo_test.txt的内容?我哪里出错了,我的代码应该是什么样子
- 使用 qunit 测试我的代码时出错
- 使用 Lodash 合并数组,为什么结果是重复的数组值?,我的代码在哪里出错
- 语法加载具有现代化 JavaScript 代码的 html 页面时出错
- 从 JavaScript 函数调用 C# 方法背后的代码时出错
- Ajax 客户端框架运行 HTML 代码时出错
- HTML代码编辑器出错
- 读取'时出错;无法读取属性'x'未定义的'在HTML5 Canvas代码中
- 为什么这个依赖于HTML5地理位置的javascript代码出错
- 使用Google Maps API和分析云代码时定义地理编码器变量时出错