使用 Jasmine 将 JavaScript 数字转换为字符串测试

标签 javascript jasmine

我正在使用 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/

相关文章:

javascript - Svelte.js - 无法正确从列表中删除项目

javascript - 通过 ajax 调用在 componentDidMount 中正确设置测试状态

javascript - 传递表示对象函数的字符串作为回调

c# - 不支持 WPF 调用脚本?

javascript - 在 JScode 中调用 HTML 对象

javascript - 使用 Value() 方法从 Firebase 检索对象

javascript - Angular 单元测试: How to check if the spied upon method is getting the correct argument?

jasmine - 设置数据库 - 与 Jasmine/Jest 的集成测试

javascript - 验证 rxjs 订阅内的方法调用

javascript - 如何在 Jasmine 的 promise 之后测试 then block 中的代码?