Code Editor
Learn TDD With Mocha

Getting Into The Red I

As you learn TDD, it may feel backwards to intentionally write and run code that will return errors. Following TDD, we write test code, the tests might fail, and when they do fail, the error messages describe the failures of our implementation code. In TDD we react to the error messages by continually re-writing our implementation code so it behaves in the way that our test specifies.

When using the red-green-refactor cycle to practice TDD, the first step is to write an expressive test describing the desired behavior of your code. It’s very important for tests to thoroughly describe the desired behavior with natural language. This will make it easy for you to understand the behavior that your test failed on.

In addition to embedding natural language in our test suite, there are various other ways to improve code’s expressiveness using the test’s native programming language.

Imagine you were trying to create the following .initials() method:

const Phrase = { initials(passPhrase){ } }

The desired behavior is that the method should return the first letter of each word in a phrase that is passed to it as an argument. The first test you could write may look like this:

describe('Phrase', () => { describe('.initials', () => { it('returns the first letter of each word in a phrase.', () => { assert.equal(Phrase.initials('Nelson Mandela'), 'NM'); }) }) })

In this example, since the test is being written before the implementation code, we would receive the following error from the test:

1) Phrase .initials should return the first letter of each word in a phrase.:
ReferenceError: Phrase is not defined

The error message tells us that the error is related to that code block. The ReferenceError tells us that the error is thrown because we don't have a Phrase object. In the next exercise, we'll show you the minimum possible code required to get this test to pass.

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