Saturday, February 13, 2016

Unit Testing Plain Old JavaScript (Part 2)

At this point we have our test runner all setup and we're ready to start writing our tests (remember that we're doing this using test-driven development).  If you're confused, check out part 1 to see how we got here.  First things first, let's write a test (spec if you're sticking with Jasmine's nomenclature):

describe('Hangman', function() {
    it('should populate alphabet with 26 characters', function() {
        buildAlphabetArray();
        
        expect(alphabet.length).toBe(26);
    });
});

After creating that if we refresh the SpecRunner.html we should see that we have an error that says buildAlphabetArray is not defined.  That's good.  That's our red (in the red-green-refactor process of TDD).  Let's fix it by creating an empty function named buildAlphabetArray (in our src/hangman.js file):

function buildAlphabetArray() {
}

Now we have a new error that says alphabet is not defined.  Because it isn't.  Let's fix that.

var alphabet;

function buildAlphabetArray() {
}

Save and refresh and we get a new error that it cannot read property length of undefined.  We've declared alphabet, but it isn't defined, initialized, or populated.  Let's fix that.

var alphabet = [];

function buildAlphabetArray() {
}

Now we finally have what we're expecting: an error that says we expected 0 to be 26.  That's because we never did populate that array.  We'll do that now.

var alphabet = [];

function buildAlphabetArray() {
    alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
}

And now our test passes.  Make sure to check out the exciting conclusion!

No comments:

Post a Comment