Code Editor
Learn TDD With Mocha

Refactor I

Congrats you're in the "green!"

Once you are "in the green" — all your tests are passing — you can confidently refactor your code. The confidence comes from knowing that our tests will catch us if we make a misstep — when refactoring, it's critical to test early if our tests turn red, then we know that something went wrong while we were refactoring, and we can undo those changes.

A good place to start with refactoring is to restructure your tests to reflect the four phases of a good test. Restructuring tests and grouping them into separate phases can improve tests regardless of whether or not they were written with TDD.

Let's consider our Phrase.initials test from earlier. We could rewrite the test with setup, exercise, and verify steps to make it more expressive and maintainable.

describe('Phrase', () => { describe('.initials', () => { it('returns the first letter of each word in a phrase.', () => { const nameInput = 'Nelson Mandela'; const expectedInitials = 'NM'; const result = Phrase.intials(inputName); assert(result, expected); }) }) })

Now that we have refactored our test code, we can refactor our implementation code. Our earlier code looked like this:

const Phrase = { initials(phr) { return 'NM'; } }

Let's make our input argument a little more expressive:

const Phrase = { initials(inputName) { return 'NM'; } }

Now, let's apply these refactoring steps to our Calculate.sum() test and method.

Report a Bug
If you see a bug or any other issue with this page, please report it here.