我正在使用 Jasmine 框架为我的 JS 代码编写一些单元测试,以了解 Jasmine 的基础知识。这更像是一个 JS 问题,而不是一个 Jasmine 问题。
我查了一下JS字符串转换方法,看了Casting to string in JavaScript 。我可能错误地使用了 toString() 。
我编写的函数如下所示:
function factorial(input) {
var result = 1;
if(input === 0) {
result = 0;
} else if(input < 0) {
result = "cannot compute factorial of negative number";
} else if(input.isString) {
result.toString();
result = "input is not a number";
} else {
for(var i = 1; i <= input; i++) {
result *= i;
}
}
return result;
}
Jasmine 规范如下:
describe("Factorializer", function() {
it("factorial() should return the correct factorial value of an input >
0.", function() {
expect.factorial(3)).toBe(6);
});
it("factorial() should return 0 if the input = 0.", function() {
expect.factorial(0)).toBe(0);
});
it("factorial() should return 1 if the input = 1.", function() {
expect.factorial(1)).toBe(1);
});
it("factorial() should return an error if the input is negative.",
function() {
expect.factorial(-5)).toBe("cannot computer factorial
negative number");
});
it("factorial() should return an error if the input is not a
number.", function() {
expect.factorial("Herro")).toBe("input is not a number");
});
it("factorial() should return an error if the input is not a
number.", function() {
expect.factorial("Herro")).toBeNaN();
});
});
只要输入是字符串,结果始终为 1。要么从未输入 else if(input.isString),要么结果没有被赋予语句中应有的值。我倾向于前者,因为前面的 else if 似乎有效(它通过了 Jasmine 测试)。最后两个 Jasmine 测试失败了,这很好,因为它证实了 Jasmine 正在工作并且我发现了我的代码的问题。
我正在尝试解决 Jasmine 发现的问题;我不会试图改变 Jasmine 测试,除非它们有问题,但我认为不存在问题。
最佳答案
将 input.isString
替换为 typeof input === 'string'
,并删除 result.toString();
。它没有做任何有用的事情。
编辑:此外,您的最后两个测试似乎是多余的。
关于使用 Jasmine 将 JavaScript 数字转换为字符串测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29013659/