Owner

This page is currently authored and maintained by noob101

Preflight

Introduction to Testing

Up till now we've introduced exercises by giving examples of what the function is supposed to do. As our functions get more complex, we need to specify in more detail what right and wrong behavior for each function looks like. One good way to do this is by writing test cases.

Testing is an extremely important part of software engineering. When you test your code, you make sure that it works. Testing also gives you a permanent record of what correct behavior for your code looks like. In the future, if someone changes your code and breaks it, your tests will reject their changes. This way, tests can help ensure that your code will keep working forever.

Developers have lots of tools they can use to make testing easy and reliable. In this section we'll introduce one of these tools, called Jest. Starting with this lesson, we'll describe exercises by showing you test cases that your solution should pass. Then in JS4, you'll learn how to write your own test cases.

Using jest

Follow these steps to create and run a test file that you can use to test your solutions to the Preflight exercises.

  1. Create a new folder (or use an existing one)

  2. We will be using the jest framework to run our tests, so we need to install it.

    npm i jest

  3. We need to setup your folder for using jest . To do that, initialize your project

    npm init -y

  4. Create a file for your solutions to this section. Call it preflight.js.

  5. Create a file for the tests. Call it preflight.test.js. The word test in the filename is important; Jest will only run files with test in the filename.

    Don't worry about what to put into this file just yet, the examples will guide you through what to put in.

  6. First tell your test file to include the file that will have your solutions:

    // fn will be an object with all your preflight solutions
    const fn = require('./preflight.js')
    

We're now ready to start writing functions. We'll do the first one step-by-step as an example.

Example

Write a function named removeCharX that removes the character at the given index from a string.