我将如何使用 Karma / Jasmine 测试 window 提示和确认?

How would I test window prompts and confirms with Karma / Jasmine?

我是 TDD 的新手,我一直在做一些来自 reddit 的编程提示来学习它。这是一个首字母缩写词生成器,它要求转换一个字符串,显示它,然后询问用户是否要生成另一个。

我的问题是我不知道如何编写测试来填写提示然后点击确定按钮。然后 select 再次询问时单击确定或取消按钮。

(function(ns, undefined)
{
    ns.generateAcronym = function()
    {
        var s = window.prompt("Enter the words to be converted into an acronym.");
        var matches = s.match(/\b(\w)/g);
        var acronym = matches.join("").toUpperCase();
        if(window.confirm("Your acronym is: "+acronym+". Would you like to generate another?"))
        {
            ns.generateAcronym();
        }

    };

})(window.pprompts = window.pprompts || {});


pprompts.generateAcronym();

好的 - 我想我明白了。如果有人有更好的方法,我很乐意 see/read 他们:)

我意识到我可以将所有这些都放在一个 it 块中,但我喜欢看到 Executed 2 of 2 SUCCESS 而不是 Executed 1 of 1 SUCCESS

describe('Acronym Generator', function() {

    beforeEach(function()
    {
        spyOn(window, "prompt").and.returnValue("Java Script Object Notation");
        spyOn(window, "confirm");
        pprompts.generateAcronym();
    });


    it('should generate a window prompt', function() {
        expect(window.prompt).toHaveBeenCalledWith("Enter the words to be converted into an acronym.");
    });

    it('should generate a confirm dialog with the proper acronym', function() {
        expect(window.confirm).toHaveBeenCalledWith("Your acronym is: JSON. Would you like to generate another?");
    });
});