I use Jest nearly every day when working, and it’s a fantastic tool. It lets me ship my code with confidence, knowing that I have produced something which works as intended.

More often than not, when I write tests for my code, I end up catching something I hadn’t considered and go back to take that into account. It saves me from getting called in the evening to fix something in production. For me, that’s a big deal.

With that said, I didn’t really know how jest worked. I used it all the time, but had no real clue what was going on under the hood.

Recently, I bought Kent C Dodd’s excellent Testing JavaScript course which has been incredible for increasing my knowledge.

As part of that, he digs into how jest works under the hood, and this encouraged me to try building my own tiny version. So I want to pass on that knowledge to you!

This will be a small series of posts on each part, but you can skip ahead and see the full repo here.

Building our test runner

Today’s focus will be building the actual test runner. This simply accepts a test with a title, and a callback. We run the callback and if there are no errors, the test passes!

If an error is thrown, then we deem the test to have failed.

Take a look:

const test = async (title: string, callback: Function) => {
  try {
    await callback();
    console.log(chalk.green(`\u2713 ${title}`));
  } catch (error) {
    console.error(chalk.red(`✕ ${title}`));
    console.error(error);
  }

So as you can see, we have our test function which accepts a title which is a string, and a callback which is the function which we want to test.

We then run our callback function in a try/catch block, and assuming that nothing is caught, we say the test has passed.

This allows us to run something like this:

test('sum adds numbers', () => {
  const sum = (a, b) => a + b
  const result = sum(3, 7)
  const expected = 10
  expect(result).toBe(expected)
})

So as you can see, we pass a title, and a function where we sum two numbers: 3 and 7. But on our final line, we see something new: expect and toBe. These are our assertions and we have nothing to handle them yet.

#jest #javascript #tdd #unit-testing #javascript-top-story #how-to-build-a-jest-clone #building-test-runner-in-jest #hackernoon-top-story

Building A Test Runner in Jest - A How-To Guide
2.50 GEEK