[英]I have no idea how to test this with Qunit?
I want to test this function: /js/lib/front.js 我想测试这个函数:/js/lib/front.js
var Front = function(){
this.onSignUp = function(){
if (!Form.assertInput("email")) {
$("input[name=email]").focus();
this.showHiddenMessage("Email not set.");
return false;
}
}
} }
I have in: /js/lib/form.js 我有:/js/lib/form.js
function Form() {
this.assertInput = function (name, defaultValue) {
var text = $("input[name=" + name + "]").val();
if (defaultValue != null) {
if (defaultValue && text == defaultValue)
return false;
}
if(this.trim(text)) return true;
return false;
}
}
This simple test passing: 这个简单的测试传递:
test("Front", function() {
var front = new Front()
ok(front);
});
But if I write something like this: 但如果我写这样的话:
test("On Sign Up ", function() {
var front = new Front()
equal(front.onSignUp(),false,"passing test");
});
I have error: Died on test #1: Form.assertInput is not a function 我有错误:死于测试#1:Form.assertInput不是一个函数
I don't understand, what I need test in function like this and how include function inside another function? 我不明白,我需要在这个函数中测试什么以及如何将函数包含在另一个函数中?
I've saved a working fiddle here . 我在这里救了一个工作小提琴。 As a side note, you might want to check out a tutorial on using qUnit, here .One thing that you need to pay attention to is when you're declaring your functions.
作为旁注,你可能想看一下使用qUnit的教程, 在这里 。你需要注意的一件事就是当你宣布你的功能时。 It's saying
Form.assertInput
is not a function because you can't access it like that. 它说
Form.assertInput
不是一个函数,因为你无法像这样访问它。 You need to use the this
keyword, which refers to current context. 您需要使用
this
关键字, this
关键字引用当前上下文。 The code should be something like this: 代码应该是这样的:
var Form = function () {
//good to have assertInput first if you're using it in a later function
this.assertInput = function (name, defaultValue) {
var text = $("input[name=" + name + "]").val();
if (defaultValue != null) {
//safer to explicitly close your if statements with {}
if (defaultValue && text == defaultValue) {
return false;
}
}
if ($.trim(text)) { return true; }
return false;
};
this.showHiddenMessage = function (message) {
alert(message);
};
this.onSignUp = function() {
//this will point to the current context, in this case it will be Form class
if (!this.assertInput("email")) {
$("input[name=email]").focus();
this.showHiddenMessage("Email not set.");
return false;
}
};
};
Also in the example code that you gave you're missing the Front
class. 同样在您给出的示例代码中,您缺少
Front
类。 So I created a dummy one in my fiddle like this: 所以我在我的小提琴中创建了一个虚拟的像这样:
var Front = function() {};
Here are the tests that were run: 以下是运行的测试:
$(document).ready(function() {
test("Front", function() {
var front = new Front();
ok(front);
});
test("On Sign Up ", function() {
var form = new Form();
equal(form.onSignUp(), false, "passing test");
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.