【问题标题】:How to write Unit Test Case for below javascript function using Jasmine如何使用 Jasmine 为以下 javascript 函数编写单元测试用例
【发布时间】:2019-04-13 03:24:37
【问题描述】:
如何使用 Jasmine 为下面的 javascript 函数编写单元测试用例?
function GetURLParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
【问题讨论】:
标签:
javascript
unit-testing
jasmine
karma-jasmine
【解决方案1】:
根据 jasmine 文档,jasmine 包含两个内容描述和规范。
describe 函数用于对相关规范进行分组,通常每个
测试文件在顶层有一个。字符串参数用于命名
规格的集合,并将与规格连接起来
规范的全名。这有助于在大型套件中查找规格。如果你
把它们命名好,你的规格在传统 BDD 中读作完整的句子
风格。
规格是通过调用全局 Jasmine 函数来定义的,它,
like describe 需要一个字符串和一个函数。字符串是标题
规范和功能是规范或测试。一个规范包含一个
或更多测试代码状态的期望。一个期待
Jasmine 中的断言是真或假。规格与
所有真正的期望都是合格的规格。具有一个或多个错误的规范
期望是一个失败的规范。
阅读更多here
你可以这样做:
function GetURLParameter(sParam) {
var sPageURL = "email=someone@example.com"; //replace it with your
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1];
}
}
}
// specs code
describe("check for url", function() {
//defining it should be something
it("should be defined", function() {
expect(GetURLParameter).toBeDefined();
});
it("should run", function() {
expect(GetURLParameter('email')).toEqual("someone@example.com");
});
});
var NOT_IMPLEMENTED = undefined;
// load jasmine htmlReporter
(function() {
var env = jasmine.getEnv();
env.addReporter(new jasmine.HtmlReporter());
env.execute();
}());
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.js"></script>
<link href="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/jasmine/1.3.1/jasmine-html.js"></script>