Click here to navigate the course.

Drag the edges to resize the window.

In Projects, you can keep track of your progress as you go throught the tasks. Check each item as you complete it!

Code Editor
Terminal
Learn
Learn TDD With Mocha

Refactor I

Congrats you're in the green!

Once you are in the green, all your tests are passing — now 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 and often — 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 tests to reflect the four phases of a good test.

Let's consider the test for our Phrase.initials method. We could rewrite the test with setup, exercise, and verification stages to make it more expressive and maintainable.

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

Here, we have re-written the same test, but we have created variables to hold the values that we will use to test the behavior of .initials(), and broken up the test into distinct phases, which are marked by the comments in the code.

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'; } }

In order to make our implementation code more expressive and clear, we can change the name of the input argument of .initials() like this:

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

Refactoring will look different for each project and at each stage of the red-green-refactor cycle. It will always involve reflecting on how to improve your code and set you up for success moving forward.

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