We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Tests

By now, you should be familiar enough with unit testing. Like anything, the more you do it, the better you will be at it. More importantly, you will begin to understand how to write code that is easier to test.

We'll use TDD for this part.

Assignment

In this course we're going to use the vitest testing framework, it's very popular and easy to setup.

npm install -D vitest
  "scripts": {
    "test": "vitest --run"
  },

The purpose of this function will be to split the user's input into "words" based on whitespace. It should also lowercase the input and trim any leading or trailing whitespace. For example:

  • hello world -> ["hello", "world"]
  • Charmander Bulbasaur PIKACHU -> ["charmander", "bulbasaur", "pikachu"]
export function cleanInput(input: string): string[] {
  // logic goes here
}

Import the cleanInput function:

import { cleanInput } from "./repl.js";

Import describe, expect and test from vitest:

import { describe, expect, test } from "vitest";

Use describe.each to create a test suite:

describe.each([
  {
    input: "  hello  world  ",
    expected: ["hello", "world"],
  },
  // TODO: more test cases here
])( // we'll do stuff here in a bit

Write the logic for the tests by looping over each case:

describe.each([
  {
    input: "  hello  world  ",
    expected: ["hello", "world"],
  },
  // TODO: more test cases here
])("cleanInput($input)", ({ input, expected }) => {
  test(`Expected: ${expected}`, () => {
    // TODO: call cleanInput with the input here

    // The `expect` and `toHaveLength` functions are from vitest
    // they will fail the test if the condition is not met
    expect(actual).toHaveLength(expected.length);
    for (const i in expected) {
      // likewise, the `toBe` function will fail the test if the values are not equal
      expect(actual[i]).toBe(expected[i]);
    }
  });
});

Run and submit the CLI tests.