javascript 使用 jasmine 对输入字段进行单元测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23735191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
unit testing for an input field using jasmine
提问by theJava
I have a form inside javascripts/fixtures/form.html
. I am checking for whether my field is empty
or contains less than eight character
or has special characters
.
我里面有一个表格javascripts/fixtures/form.html
。我正在检查我的字段是否empty
包含less than eight character
或具有special characters
.
it("Username should not be empty", function(){
spyOn($("#name"), "val").and.returnValue("Java");
var result = $("#name").val();
expect(result).toEqual("Java");
});
it("Username should be of the length greater than eight", function(){
spyOn($("#name"), "val").and.returnValue("Java");
var result = $("#name").val();
expect(result).toEqual("Java");
});
it("Username should not contain special characters", function(){
spyOn($("#name"), "val").and.returnValue("Java");
var result = $("#name").val();
expect(result).toEqual("Java");
});
I am not sure whether this is the right way to do unit testing. Can anyone guide me on how to do unit testing for an input field on these three cases.
我不确定这是否是进行单元测试的正确方法。谁能指导我如何在这三种情况下对输入字段进行单元测试。
回答by user3428816
You can not check the input data directly with this:
你不能直接用这个检查输入数据:
var result = $("#name").val();
expect(result).toEqual("Java");
To check your input field value, you can load/set the fixtures and can assign the value to your fixtures and can read the fixtures' input data then you can check with .toEqual("") or something else.
要检查您的输入字段值,您可以加载/设置灯具并可以将值分配给您的灯具并可以读取灯具的输入数据,然后您可以使用 .toEqual("") 或其他方法进行检查。
You can refer this code to check the input field value:
您可以参考此代码来检查输入字段值:
var value = 'some value';
var differentValue = 'different value';
beforeEach(function () {
setFixtures($('<input id="sandbox" type="text" />').val(value));
});
it("should pass if value matches expectation", function () {
expect($('#sandbox')).toHaveValue(value);
expect($('#sandbox').get(0)).toHaveValue(value);
});
I hope this url will help you bit more to understand the fixtures: https://github.com/velesin/jasmine-jquery/#cross-domain-policy-problems-under-chrome
我希望这个 url 能帮助你更多地了解灯具:https: //github.com/velesin/jasmine-jquery/#cross-domain-policy-problems-under-chrome