Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Run a Simple Test with Jest in a React App

    Andy Van SlaarsAndy Van Slaars
    jestJest

    Testing should be part of any substantial project, so we'll take the effort out of it by incorporating testing configuration into our boilerplate. In this lesson, we'll add Jest as a project dependency. We’ll add a test script to our package.json, create a sample test and verify that our test script works.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: Any time I start a new project from this boilerplate, I'd like to be set up to run test. We're going to do that with Jest. I'm going to do an npm i -D, to save as a dev dependency, jest.

    With that installed, let's open up the package.json file. In my scripts, I'm going to update this test script. I'm going to remove this default script. I'm going to replace it with Jest. We can save that.

    Back in the terminal, I'm going to do an npm test to run the script. When I do this, I'm going to get an error that no tests were found. Let's create our first test file. We can either put tests in an tests directory, or we can colocate them. We can use the .spec or .test.js extension.

    I'm going to colocate my tests. In source, I'm just going to add a new file. I'm going to call it app.spec.js. In this file, I'm going to start with a describe block. Describe is going to take a string for what we're testing. In this case, it'll be our app component and a function. I'll just use an error function here.

    Then we can use either test or it to define an individual test. For now, we're just going to put in a test that passes. We're just going to say, "It runs and passes." This isn't going to be a valuable test, but it'll allow us to test our Jest script.

    In here, I'm just going to say that I expect true to be true. I can save that file. Back in the terminal, I'm going to npm test again. That's going to run our app.spec.js. We'll see that it passes.

    If I want to make sure that it can fail, I can just come in here and make an expectation that can't possibly pass. We'll npm test one more time. Our test fails. Let's fix that, npm test. Now we have a passing test and a working test script.