This site runs best with JavaScript enabled.

But really, what is a JavaScript test?


Let's take a step back and understand automated testing of JavaScript from square one.

Testing software. There are a ton of reasons we do it. Here are a two of mine:

  1. Speeds up my workflow so I can develop software faster
  2. Helps me ensure I don't break existing code when making changes

That said, I have a few questions for you (these are twitter polls):

The goal of this post is to get each of you to be able to answer "Yes" to that last question. So you have a fundamental understanding of what a test in JavaScript even is which will help you write better tests.

So what we're going to do is take this simple math.js module and write tests for the two functions it exposes:

1const sum = (a, b) => a + b
2const subtract = (a, b) => a - b
3
4module.exports = {sum, subtract}

I've made a repo on GitHub you can reference as well ๐Ÿ™๐Ÿ˜ธ

Step 1

Here's the most basic form of a test I can think of:

1// basic-test.js
2const actual = true
3const expected = false
4if (actual !== expected) {
5 throw new Error(`${actual} is not ${expected}`)
6}

You could run this test code by running node basic-test.js! That's a test! ๐ŸŽ‰

A test is code that throws an error when the actual result of something does not match the expected output. It can get more complicated when you're dealing with code that depends on some state to be set up first (like a component needs to be rendered to the document before you can fire browser events, or there needs to be users in the database). However, it is relatively easy to test "pure functions" like those in our math.js module (functions which will always return the same output for a given input and not change the state of the world around them).

The part that says actual !== expected is called an "assertion." It's a way to say in code that one thing should be a certain value or pass a certain... eh... testย :) It could be an assertion that the actual matches a regex, is an array with a certain length, or any number of things. The key is that if our assertion fails, then we throw an error.

So here's what the most basic test would be for our math.jsfunction:

1// 1.js
2const {sum, subtract} = require('./math')
3
4let result, expected
5
6result = sum(3, 7)
7expected = 10
8if (result !== expected) {
9 throw new Error(`${result} is not equal to ${expected}`)
10}
11
12result = subtract(7, 3)
13expected = 4
14if (result !== expected) {
15 throw new Error(`${result} is not equal to ${expected}`)
16}

There you go! Run that with node and the command will exit without error. Now, let's break the sum function by changing the + to a - and run it again and we'll see:

1$ node 1.js
2/Users/kdodds/Desktop/js-test-example/1.js:8
3 throw new Error(`${result} is not equal to ${expected}`)
4 ^
5
6Error: -4 is not equal to 10
7 at Object.<anonymous> (/Users/kdodds/Desktop/js-test-example/1.js:8:9)
8 at Module._compile (module.js:635:30)
9 at Object.Module._extensions..js (module.js:646:10)
10 at Module.load (module.js:554:32)
11 at tryModuleLoad (module.js:497:12)
12 at Function.Module._load (module.js:489:3)
13 at Function.Module.runMain (module.js:676:10)
14 at startup (bootstrap_node.js:187:16)
15 at bootstrap_node.js:608:3

Cool! We're benefitting from our basic tests already! We can't break the sum function without breaking our automated test! Neato!

One of the most important parts of testing frameworks (or assertion libraries) is how helpful their error messages are. Often when a test fails, the first thing you'll see is the error message. If you can't figure out what the underlying problem is from the error message, then you have to spend a few minutes looking at the code to understand what went wrong. A lot of the quality of the error message depends on how well you understand and use the assertions provided by the framework you're using.

Step 2

Did you know that Node actually has an assert module for making assertions like the one we have above ๐Ÿค”? Let's refactor our test to use that module!

1// 2.js
2const assert = require('assert')
3const {sum, subtract} = require('./math')
4
5let result, expected
6
7result = sum(3, 7)
8expected = 10
9assert.strictEqual(result, expected)
10
11result = subtract(7, 3)
12expected = 4
13assert.strictEqual(result, expected)

Nice! This is still a test module. This is functionally equivalent to what we had before. The only difference is the error message:

1$ node 2.js
2assert.js:42
3 throw new errors.AssertionError({
4 ^
5
6AssertionError [ERR_ASSERTION]: -4 === 10
7 at Object.<anonymous> (/Users/kdodds/Desktop/js-test-example/2.js:8:8)
8 at Module._compile (module.js:635:30)
9 at Object.Module._extensions..js (module.js:646:10)
10 at Module.load (module.js:554:32)
11 at tryModuleLoad (module.js:497:12)
12 at Function.Module._load (module.js:489:3)
13 at Function.Module.runMain (module.js:676:10)
14 at startup (bootstrap_node.js:187:16)
15 at bootstrap_node.js:608:3

You'll notice that the error thrown no longer includes any of our own code in it which is a shame... ๐Ÿ˜ฆ But let's keep going.

Step 3

Let's go ahead and write our own simple testing "framework" and assertion library. We'll start with the assertion library. So instead of Node's built-in assert module we'll create a library we'll call expect. Here's our refactored test with that change:

1// 3.js
2const {sum, subtract} = require('./math')
3
4let result, expected
5
6result = sum(3, 7)
7expected = 10
8expect(result).toBe(expected)
9
10result = subtract(7, 3)
11expected = 4
12expect(result).toBe(expected)
13
14function expect(actual) {
15 return {
16 toBe(expected) {
17 if (actual !== expected) {
18 throw new Error(`${actual} is not equal to ${expected}`)
19 }
20 },
21 }
22}

Cool, so now we can add a bunch of assertions on that object we return (like toMatchRegex or toHaveLength). Oh, and here's the error message now:

1$ node 3.js
2/Users/kdodds/Desktop/js-test-example/3.js:17
3 throw new Error(`${actual} is not equal to ${expected}`)
4 ^
5
6Error: -4 is not equal to 10
7 at Object.toBe (/Users/kdodds/Desktop/js-test-example/3.js:17:15)
8 at Object.<anonymous> (/Users/kdodds/Desktop/js-test-example/3.js:7:16)
9 at Module._compile (module.js:635:30)
10 at Object.Module._extensions..js (module.js:646:10)
11 at Module.load (module.js:554:32)
12 at tryModuleLoad (module.js:497:12)
13 at Function.Module._load (module.js:489:3)
14 at Function.Module.runMain (module.js:676:10)
15 at startup (bootstrap_node.js:187:16)
16 at bootstrap_node.js:608:3

Ok, things are looking good.

Step 4

But now here's the problem ๐Ÿ˜–... If I see that error message, how do I know that the sum function is the one that's broken? It could be the subtract module. Also, the source of the test doesn't do a good job of keeping tests isolated (visually or otherwise).

So let's write a helper function to make that work:

1// 4.js
2const {sum, subtract} = require('./math')
3
4test('sum adds numbers', () => {
5 const result = sum(3, 7)
6 const expected = 10
7 expect(result).toBe(expected)
8})
9
10test('subtract subtracts numbers', () => {
11 const result = subtract(7, 3)
12 const expected = 4
13 expect(result).toBe(expected)
14})
15
16function test(title, callback) {
17 try {
18 callback()
19 console.log(`โœ“ ${title}`)
20 } catch (error) {
21 console.error(`โœ• ${title}`)
22 console.error(error)
23 }
24}
25
26function expect(actual) {
27 return {
28 toBe(expected) {
29 if (actual !== expected) {
30 throw new Error(`${actual} is not equal to ${expected}`)
31 }
32 },
33 }
34}

Now we can put everything relevant to a given test within our "test" callback function and we can give that test a name. Then we use that test function to not only give a more helpful error message but also run all the tests in the file (without bailing on the first error)! Here's the output now:

1$ node 4.js
2โœ• sum adds numbers
3Error: -4 is not equal to 10
4 at Object.toBe (/Users/kdodds/Desktop/js-test-example/4.js:29:15)
5 at test (/Users/kdodds/Desktop/js-test-example/4.js:6:18)
6 at test (/Users/kdodds/Desktop/js-test-example/4.js:17:5)
7 at Object.<anonymous> (/Users/kdodds/Desktop/js-test-example/4.js:3:1)
8 at Module._compile (module.js:635:30)
9 at Object.Module._extensions..js (module.js:646:10)
10 at Module.load (module.js:554:32)
11 at tryModuleLoad (module.js:497:12)
12 at Function.Module._load (module.js:489:3)
13 at Function.Module.runMain (module.js:676:10)
14โœ“ subtract subtracts numbers

Sweet! Now we see the error itself and we see the title of the test so we know which one to go about fixing.

Step 5

So all we need to do now is write a CLI tool that will search for all our test files and run them! That bit is pretty simple at first, but there are a LOT of things we can add on top of it. ๐Ÿ˜…

At this point, we're building a testing framework and test runner. Luckily for us, there are a bunch of these built already! I've tried a ton of them and they're all great. That said, nothing comes close to serving my use cases better than Jest ๐Ÿƒ. It's an amazing tool (learn more about Jest here).

So, instead of building our own framework, let's just go ahead and switch our test file to work with Jest. As it so happens, it already does! All we have to do is remove our own implementation of test and expect because Jest includes those in our tests as global objects! So here's what it looks like now:

1// 5.js
2const {sum, subtract} = require('./math')
3
4test('sum adds numbers', () => {
5 const result = sum(3, 7)
6 const expected = 10
7 expect(result).toBe(expected)
8})
9
10test('subtract subtracts numbers', () => {
11 const result = subtract(7, 3)
12 const expected = 4
13 expect(result).toBe(expected)
14})

When we run this file with Jest, here's what the output looks like:

1$ jest
2 FAIL ./5.js
3 โœ• sum adds numbers (5ms)
4 โœ“ subtract subtracts numbers (1ms)
5
6โ— sum adds numbers
7
8expect(received).toBe(expected)
9
10 Expected value to be (using Object.is):
11 10
12 Received:
13 -4
14
15 4 | const result = sum(3, 7)
16 5 | const expected = 10
17 > 6 | expect(result).toBe(expected)
18 7 | })
19 8 |
20 9 | test('subtract subtracts numbers', () => {
21
22 at Object.<anonymous>.test (5.js:6:18)
23
24Test Suites: 1 failed, 1 total
25Tests: 1 failed, 1 passed, 2 total
26Snapshots: 0 total
27Time: 0.6s, estimated 1s
28Ran all test suites.

You can't tell from the text, but that output is colored. Here's an image of the output:

Screenshot of the output from runningย jest

It has color coding which is really helpful in identifying the parts that are relevant ๐Ÿ˜€ It also shows the code where the error was thrown! Now that's a helpful error message!

Conclusion

So, what's a JavaScript test? It's simply some code which sets up some state, performs some action, and makes an assertion on the new state. We didn't talk about common framework helper functions like beforeEach or describe, and there are a lot more assertions we could add like toMatchObject or toContain. But hopefully this gives you an idea of the fundamental concepts of testing with JavaScript.

I hope this is helpful to you! Good luck! ๐Ÿ‘

Discuss on Twitter โ€ข Edit post on GitHub

Share article
loading relevant upcoming workshops...

TestingJavaScript.com

Your essential guide to flawless testing.

Jump on this self-paced workshop and learn the smart, efficient way to test any JavaScript application. ๐Ÿ†

Start Now
Kent C. Dodds

Kent C. Dodds is a JavaScript software engineer and teacher. He's taught hundreds of thousands of people how to make the world a better place with quality software development tools and practices. He lives with his wife and four kids in Utah.