Search code examples
javascripttddkarma-jasminee2e-testing

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


I'm pretty new to TDD and I've been doing some programming prompts from reddit to learn it. This one is an acronym generator that asks for a string to be converted, displays it, and then asks if the user wants to generate another.

My trouble is that I don't know how to write the tests to fill in the prompt and then hit the ok button. Then select the ok or cancel button when asked again.

(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();

Solution

  • Alright - I think I figured this out. If anyone has better methods, I'd love to see/read them :)

    I realize I could have put all of this into one it block, but I like seeing the Executed 2 of 2 SUCCESS over 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?");
        });
    });