Creating My First Unit Tests with Jest

theoluyi

theoluyi

Posted on October 2, 2020

Creating My First Unit Tests with Jest

When I first started coding I always appreciated the satisfaction of passing tests and getting those snazzy green checkmarks in the terminal. Even the red x of failure I appreciated in his blunt honesty: speaking clearly to me, saying, “why don’t you try that again, sir.”

I remember feeling disappointed when I progressed further with programming and realized that these reassuring little guys didn’t just populate the inside of my computer like angry red devils and supportive green smurfs, that it was in fact possible to veer into the dark abyss of the terminal with no external reference points for correctness or accuracy to the thing I was actually trying to write.

The technical stuff is at the bottom, do yourself a favor and skip this middle part smh

But in the battle-blur of bootcamp, I had to keep my eye at the ready for any code challenge waiting to pounce and rip my head off, any quirk of JS I might fail to pick up in lecture that might lock me in a virtual cage like Matilda in the Chokey. The vagueness bothered me, but I moved forward and wrote messy, untested code with wild abandon; I swam with the code currents, the widening gyre.

After I read Eric Elliot’s article TDD Changed My Life, however, I knew that there was something out there that would fill this code void in my soul.

I was scared, but intrigued. Was there something wrong with me? Nobody else liked testing. Was this normal? Everyone else seemed to forge on ahead, brandishing their programming pistols and coding cutlasses with confidence. But eventually I had to admit it: I was curious about Test Driven Development. Google was my point of entry into self-acceptance and a whole new world.

But seriously I want to finish writing this post so let’s get to some technical stuff.

I worked on a codealong called Jest Tutorial for Beginners: Getting Started With JavaScript Testing from Valentino Gagliardi.

To start with the most basic idea, in testing our code, we want to verify that our code actually does what we expect it to do. It naturally follows from this that the way we make tests is by creating example inputs and example outputs that model the transformation we want the function to perform.

Then we essentially run the ACTUAL function with the example input and see if the function ACTUALLY produces the output we want. If it doesn’t, then the test doesn't pass, which means WE DID IT. We made a test that fails, because the function doesn’t exist yet. Only the test does. In this way, we start with the test, and let that drive us toward working code that passes it. It’s simple but brilliant for structuring the problem-solving process and approach.

We can use several key methods in Jest to accomplish this: describe, test, and expect.

  • describe is a Jest method for containing related tests. For example, in this tutorial, the first test I created verifies whether or not a filter function correctly filters an array of objects based on a search term. Describe takes two arguments: 1) a string describing the test suite (a test suite is just a bunch of test methods testing different aspects of the function), and 2) a callback that wraps the actual tests
  • test is another method which like describe takes a string and a callback. The string describes the particular test, and the callback wraps more code, such as variable declarations and statements using the next keyword: expect. expect is where the real nuts and bolts of testing become visible.
  • expect is where we perform the comparison of the function’s actual output to the output we would like it to have
  • so we have a 3 part nesting: describe contains test statements, and a test statement contains expect statements (if I am misusing the term statement here I apologize)

It’s much clearer to follow with the code, so I am copying it here; the tutorial is Valentino Gagliardi’s so if you’d like to work on it yourself click here: Jest Tutorial for Beginners: Getting Started With JavaScript Testing

// begin tests
describe("Filter function", () => {

    //test stuff goes in here
    test("it should filter by a search term (link)", () => {
        //actual test

        const input = [
            { id: 1, url: "https://www.url1.dev" },
            { id: 2, url: "https://www.url2.dev" },
            { id: 3, url: "https://www.link3.dev" },
        ]; // end of const input varDeclare

        const output = [ { id: 3, url: "https://www.link3.dev" }];
        const output2 = [ 
            { id: 1, url: "https://www.url1.dev" },
            { id: 2, url: "https://www.url2.dev" } 
        ]

        expect(filterByTerm(input, "link")).toEqual(output); 

        expect(filterByTerm(input, "LINK")).toEqual(output); // new test for case insensitivity

        expect(filterByTerm(input, "uRl")).toEqual(output2);

        expect(filterByTerm(input, "")).toEqual(input)
    }); // end of test block
Enter fullscreen mode Exit fullscreen mode

Here is the function that the above code is testing

function filterByTerm(inputArr, searchTerm) {

    // case insensitive reg expression evolves from searchTerm
    const regex = new RegExp(searchTerm, 'i'); 

    return inputArr.filter( function(arrayElement) {
        return arrayElement.url.match(regex)
    })
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
theoluyi
theoluyi

Posted on October 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related