如何在Jasmine中运行js函数
How to run a js function in Jasmine?
我可以在js文件上运行jasmine测试,但似乎无法在测试框架内运行任何函数。
这是JS文件jasmine_test.JS
$(document).ready(function() {
function hello(){
console.log("yo")
}
hello()
});
这是form_detail_spec.js
describe("tthe things", function(){
it("testing the things", function(){
var array = ["one"];
//isOptionalEmailForm(array);
//expect(isOptionalEmailForm(array)).toBe(true);
hello()
expect(1).toBe(1);
});
});
当我运行规范文件时,我在jasmine控制台中得到以下错误:
ReferenceError: hello is not defined
规范没有通过。如果我从测试中删除hello(),它会很好地工作。
这是specrunner.html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jasmine Spec Runner v2.2.0</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-2.2.0/jasmine_favicon.png">
<link rel="stylesheet" href="lib/jasmine-2.2.0/jasmine.css">
<script type="text/javascript" src="../js/vendor/jquery/jquery-1.11.2.js"></script>
<script src="lib/jasmine-2.2.0/jasmine.js"></script>
<script src="lib/jasmine-2.2.0/jasmine-html.js"></script>
<script src="lib/jasmine-2.2.0/boot.js"></script>
<script type="text/javascript" src="../js/vendor/bootstrap/bootstrap.min.js"></script>
<script type="text/javascript" src="../js/vendor/bootstrap/bootstrapValidator.min.js"></script>
<script type="text/javascript" src="../js/validator_parameters.js"></script>
<!-- include source files here... -->
<!-- <script src="src/Player.js"></script> -->
<!-- <script src="src/Song.js"></script> -->
<script src="../js/jasmine_test.js"></script>
<!-- include spec files here... -->
<!-- <script src="spec/SpecHelper.js"></script> -->
<!-- <script src="spec/PlayerSpec.js"></script> -->
<script src="spec/form_details_spec.js"></script>
</head>
<body>
</body>
</html>
函数hello
位于另一个函数内部。它不暴露在外界,所以你无法直接测试它。把你的函数写成模块真的很好,比如CommonJS、AMD或新的ES6模块,然后测试这些模块。
这就是使用CommonJS/NodeJS 编写和访问模块的方式
// hello.js
module.exports = hello; // export your function as a module
function hello() {
// code here
}
// test.js
var hello = require('./path/to/hello'); // you don't need to write the .js extension
// you can now call `hello()` in your test code here.
不太理想、更传统的方法是让hello
函数不可避免地从全局范围访问。想想jQuery,您可以从jQuery
或$
全局变量访问它的函数。
// your-file.js
var myLib = {
hello: function() {
// code
}
}
然后包括your-file.js
,以便myLib
变量全局可用。然后您可以使用myLib.hello()
从那里访问hello
。或者你可以让hello
成为一个全局变量/函数,但这真的很糟糕。
模块现在是最佳实践。由于NodeJs是基于CommonJS模块的,所以我使用Browserify将CommonJS模块带到客户端,并用磁带测试所有内容,这也是一个CommonJS模块。
相关文章:
- 如何使用Gmail运行.js文件
- 当运行JS函数时,如何在c#中的Edgejs中获取错误文本
- 按钮未运行为按钮,找不到如何使运行JS文件
- 在单独的上下文中运行 js 代码并访问其全局变量
- 如何使用 GetValues 使用 Jint 运行 Js 代码
- 节点webkit仅运行.js文件
- 如何在Jasmine中运行js函数
- Ubuntu试图运行.js文件得到抛出错误;
- 在pink-in上运行js;在pink-out上运行不同的js
- 加载图像后运行JS
- 从命令行运行JS文件
- 如何在命令提示符下运行js文件
- Meteor/Iron路由器-何时何地运行JS以交换到所见即所得
- 按顺序运行Js代码
- 在终端中使用imacros运行JS
- 无法在 Windows 上的节点中运行.js文件
- 如何使用 Muse 参数进行布尔比较以运行 JS 函数
- 运行 JS 对象列表
- 防止动画多次运行 - js 回调
- 从子窗口的父窗口运行JS函数