myHotTake

Tag: write test

  • How to Write Your First JavaScript Test with Jest or Mocha

    If you enjoy this story and find it helpful, feel free to like or share it with anyone who might be embarking on their own coding adventure!


    I’m a detective in the city of JavaScriptopolis, where mysteries and problems lurk in every snippet of code. One day, I’m tasked with solving a curious case: ensuring that a new algorithm designed to solve a problem actually works as intended. This is where I summon the power of Jest, my trusty magnifying glass, or Mocha, my reliable notebook, to write my very first test.

    I begin my investigation by setting the scene. In Jest, I create a new file for my test case, like opening a fresh page in my detective journal. I name it something catchy, like algorithm.test.js, so it stands out in the cluttered evidence room of my project directory. If Mocha is my tool of choice, I ensure I have a similar setup, maybe even with a cup of coffee by my side, just like the name suggests.

    Now, I step into the shoes of a storyteller, crafting a tale that describes the problem my algorithm is meant to solve. I wrap my story in a describe block, which frames the context of my investigation. Within this narrative, I write an it block—a vivid scene depicting what should happen when my algorithm tackles the problem. It’s here that I specify an expectation, like declaring, “I expect the sum of 2 and 2 to be 4.” This is my hypothesis, the truth I seek to verify.

    Armed with my Jest magnifying glass, I call upon the expect function, peering closely at the algorithm’s output. Or, with Mocha, I might use an assertion library like Chai to express my expectations. Both are my trusty sidekicks, helping me determine if the narrative matches reality. If the algorithm performs as anticipated, it’s like hearing applause from the audience of code reviewers. If not, well—it’s back to the drawing board, refining the plot until the mystery is solved.


    In Jest, I begin by setting up my test environment. I include the function I want to test, either by importing it from another file or defining it within my test file. Here’s how I might write my test:

    // algorithm.js
    function add(a, b) {
      return a + b;
    }
    
    module.exports = add;
    // algorithm.test.js
    const add = require('./algorithm');
    
    describe('add function', () => {
      it('should return the sum of two numbers', () => {
        expect(add(2, 2)).toBe(4);
        expect(add(-1, 1)).toBe(0);
        expect(add(0, 0)).toBe(0);
      });
    });

    In this code, I use Jest’s describe block to set the context, much like framing the narrative of my investigation. Inside, the it block describes the expected outcome: that the add function should correctly sum two numbers. I use expect to declare my expectations, like a detective verifying a suspect’s alibi.

    If I were using Mocha, the setup would be slightly different, but the essence remains the same. I might use Chai for assertions:

    // algorithm.js
    function add(a, b) {
      return a + b;
    }
    
    module.exports = add;
    // algorithm.test.js
    const { expect } = require('chai');
    const add = require('./algorithm');
    
    describe('add function', () => {
      it('should return the sum of two numbers', () => {
        expect(add(2, 2)).to.equal(4);
        expect(add(-1, 1)).to.equal(0);
        expect(add(0, 0)).to.equal(0);
      });
    });

    Here, Mocha’s describe and it perform a similar role, while Chai’s expect helps me make assertions about add’s behavior.

    Key Takeaways:

    1. Testing Frameworks: Jest and Mocha are powerful tools to ensure your code behaves as expected. Jest integrates smoothly with JavaScript projects, while Mocha allows for flexible configurations with various assertion libraries like Chai.
    2. Describe and It Blocks: These are fundamental in structuring your tests, allowing you to separate different parts of your investigation clearly.
    3. Assertions: Use assertions to express the conditions that must be true for your code to be considered correct. They are like checkpoints in your detective story, ensuring every step is logical and accurate.
    4. Iteration and Improvement: Writing tests is an iterative process. As you refine your algorithm, your tests will evolve, serving as a reliable companion in your coding journey.