TEST DRIVEN DEVELOPMENT:

UNIT TESTS

LEARNING OBJECTIVES

- Set up a test environment

 

- Write a test and watch it fail (RED)

- Add MINIMAL code to pass the test (GREEN)

- Refactor if needed, Run the test again (GREEN?)

 

- Add edge case test (RED)

- Add minimal code to pass the test (GREEN)

- Refactor (GREEN)

 

Rinse & Repeat

1. Create a file called yellPhrase.js at the project root

 

2. Create a folder called test at the project root


3. Inside of test, create a file called yellPhraseTest.js


4. In the command line, in the project root run:

  - npm init -y
  - npm install mocha chai --save-dev

 

Test Environment

5. Change scripts in package.json to:
      "scripts": {
        "test": "mocha"
      },

 

6. In yellPhrase.js, require the test frameworks:
       const chai = require('chai')

       const assert = chai.assert

       /* eslint-env node, mocha */

 

Test Environment

We are writing a function called yellPhrase that converts a string to all caps.

 

1. Write the test

2. npm test - what do we expect?

Write the test:

We are writing a function called yellPhrase that converts a string to all caps.

 

Add MINIMAL code to pass the test

 

1. Write the function

  - module.exports the function

     module.exports = { yellPhrase }
  - require the function in the test file

     const yellPhrase = require('../yellPhrase').yellPhrase

 

2. npm test, what do we expect?

Write the function:

 - Adds NO new functionality

- Clean up the code

- Make sure it still passes

 

Is it needed here?

Refactor

Wait, WHAT?

That is not right...

Yes- it can be better

Add a case

We are writing a function called yellPhrase that converts a string to all caps.

 

Refactor to account for params, Run the test again

 

1. Update the function

2. npm test, what do we expect?

Second Case

The function should display a message if given
a non-string input

 

1. Add to the test

2. npm test, what do we expect?

Edge case 1:

The function should display a message if given
a non-string input

 

1. Update the function to pass the test

2. npm test, what do we expect?

Edge case 1:

The function should display a message if no input is given

 

1. Add to the test

2. npm test, what do we expect?

Edge case 2:

The function should display a message if no input is given

 

1. Update the function to pass the test

2. npm test, what do we expect?

Edge case 2:

Can we make the code better?

Edge case 2, Refactor

LEARNING OBJECTIVES

- Set up a test environment

 

- Write a test and watch it fail (RED)

- Add MINIMAL code to pass the test (GREEN)

- Refactor to be modular, Run the test again (GREEN?)

 

- Add edge case test (RED)

- Add minimal code to pass the test (GREEN)

- Refactor (GREEN)

 

Rinse & Repeat

Unit Tests

By Michelle Bergquist

Unit Tests

  • 93
Loading comments...

More from Michelle Bergquist