This site runs best with JavaScript enabled.

AHA Testing 💡


How to apply the "Avoid Hasty Abstraction" principle to your test code.

The AHA Programming Principle stands for "Avoid Hasty Abstraction." I have specific feelings about how this applies to writing maintainable tests. Most of the tests that I've seen in the wild have been wildly on one side of the spectrum of abstraction: ANA (Absolutely No Abstraction), or completely DRY (Don't Repeat Yourself). (I made up ANA just now).

ANA(Absolutely No Abstraction)
AHA(Avoid Hasty Abstraction)
DRY(Don't Repeat Yourself)
TheSpectrumofAbstraction

Finding a sweet spot in the middle of the spectrum of abstraction is key to developing maintainable tests.

ANA Testing

The best example of "Absolutely No Abstraction" I've seen in testing is for ExpressJS route handlers. For you to understand what I mean when I say "ANA is bad for testing" I'm going to give you a typical test file and ask you to pretend you're going to maintain this codebase and these tests. It's important for you to understand how this route works. You're relieved that there are tests in place which will help you make sure you're not going to break something. So now you're going to use the tests to understand the nuances of the route handler.

Try to read this test and understand the one nuance between the two of them.

Don't spend too long on this...

1import * as blogPostController from '../blog-post'
2
3// load the application-wide mock for the database.
4// I guess that means this is AANA (Almost Absolutely No Abstraction)
5// but I didn't want to write out a whole db mock for this blog post 😅
6jest.mock('../../lib/db')
7
8test('lists blog posts for the logged in user', async () => {
9 const req = {
10 locale: {
11 source: 'default',
12 language: 'en',
13 region: 'GB',
14 },
15 user: {
16 guid: '0336397b-e29d-4b63-b94d-7e68a6fa3747',
17 isActive: false,
18 picture: 'http://placehold.it/32x32',
19 age: 30,
20 name: {
21 first: 'Francine',
22 last: 'Oconnor',
23 },
24 company: 'ACME',
25 email: 'francine.oconnor@ac.me',
26 latitude: 51.507351,
27 longitude: -0.127758,
28 favoriteFruit: 'banana',
29 },
30 body: {},
31 cookies: {},
32 query: {},
33 params: {
34 bucket: 'photography',
35 },
36 header(name) {
37 return {
38 Authorization: 'Bearer TEST_TOKEN',
39 }[name]
40 },
41 }
42 const res = {
43 clearCookie: jest.fn(),
44 cookie: jest.fn(),
45 end: jest.fn(),
46 locals: {
47 content: {},
48 },
49 json: jest.fn(),
50 send: jest.fn(),
51 sendStatus: jest.fn(),
52 set: jest.fn(),
53 }
54 const next = jest.fn()
55
56 await blogPostController.loadBlogPosts(req, res, next)
57
58 expect(res.json).toHaveBeenCalledTimes(1)
59 expect(res.json).toHaveBeenCalledWith({
60 posts: expect.arrayContaining([
61 expect.objectContaining({
62 title: 'Test Post 1',
63 subtitle: 'This is the subtitle of Test Post 1',
64 body: 'The is the body of Test Post 1',
65 }),
66 ]),
67 })
68})
69
70test('returns an empty list when there are no blog posts', async () => {
71 const req = {
72 locale: {
73 source: 'default',
74 language: 'en',
75 region: 'GB',
76 },
77 user: {
78 guid: '0336397b-e29d-4b63-b94d-7e68a6fa3747',
79 isActive: false,
80 picture: 'http://placehold.it/32x32',
81 age: 30,
82 name: {
83 first: 'Francine',
84 last: 'Oconnor',
85 },
86 company: 'ACME',
87 email: 'francine.oconnor@ac.me',
88 latitude: 31.230416,
89 longitude: 121.473701,
90 favoriteFruit: 'banana',
91 },
92 body: {},
93 cookies: {},
94 query: {},
95 params: {
96 bucket: 'photography',
97 },
98 header(name) {
99 return {
100 Authorization: 'Bearer TEST_TOKEN',
101 }[name]
102 },
103 }
104 const res = {
105 clearCookie: jest.fn(),
106 cookie: jest.fn(),
107 end: jest.fn(),
108 locals: {
109 content: {},
110 },
111 json: jest.fn(),
112 send: jest.fn(),
113 sendStatus: jest.fn(),
114 set: jest.fn(),
115 }
116 const next = jest.fn()
117
118 await blogPostController.loadBlogPosts(req, res, next)
119
120 expect(res.json).toHaveBeenCalledTimes(1)
121 expect(res.json).toHaveBeenCalledWith({
122 posts: [],
123 })
124})

Did you find the difference? Yeah! We expect to find a post in the first one and not in the second one! Cool! Great job. But... what causes that? Why does blogPostController.loadBlogPosts(req, res, next) call res.json with a blog post in the first one and not in the second one?

If you didn't figure that out, don't feel bad and don't worry, I'll show you later. If you did, you're probably really good at "Where's Wally" and that's my point. Tests like this make it harder than it needs to be to understand and maintain the tests.

Now imagine that there are twenty such tests in a single file. You think it's terrible? Yes, it's pretty bad. Never seen tests like this before? You're lucky! I've seen it a lot. Here's how it gets this way:

  1. Engineer Joe joins a team
  2. Joe needs to add a test
  3. Joe copies a previous test that looks like what they need and modifies it for their use case.
  4. Reviewers observe that the tests pass and assume Joe knows what they're talking about.
  5. PR is merged.

Here's your litmus test:

How easy is it to determine the difference between assertions of two similar tests and what causes that difference?

Absolutely No Abstraction testing makes this very difficult.

DRY Testing

I don't have time at the moment to give you a good example of a DRY test. Just know that often what happens when people apply DRY to anything they typically wind up being harder to maintain due to this process:

  1. Engineer Joe joins a team
  2. Joe needs to add a test
  3. Joes copies a previous test that looks basically exactly like what they need and adds another if statement to the testing utility for their case.
  4. Reviewers observe that the tests pass and assume Joe knows what they're talking about.
  5. PR is merged.

Another thing that I see a lot in DRY testing is the overuse of describe and it nesting + beforeEach. The more you nest and use shared variables between tests, the harder it is to follow the logic. I write about this problem a little bit in Test Isolation with React which I recommend you read.

AHA Testing

That first test is absolutely screaming for abstraction (which is the guiding principle for AHA programming). So let's write a thoughtful abstraction for that test. Now try to figure out what makes the difference in these tests:

1import * as blogPostController from '../blog-post'
2
3// load the application-wide mock for the database.
4jest.mock('../../lib/db')
5
6function setup(overrides = {}) {
7 const req = {
8 locale: {
9 source: 'default',
10 language: 'en',
11 region: 'GB',
12 },
13 user: {
14 guid: '0336397b-e29d-4b63-b94d-7e68a6fa3747',
15 isActive: false,
16 picture: 'http://placehold.it/32x32',
17 age: 30,
18 name: {
19 first: 'Francine',
20 last: 'Oconnor',
21 },
22 company: 'ACME',
23 email: 'francine.oconnor@ac.me',
24 latitude: 51.507351,
25 longitude: -0.127758,
26 favoriteFruit: 'banana',
27 },
28 body: {},
29 cookies: {},
30 query: {},
31 params: {
32 bucket: 'photography',
33 },
34 header(name) {
35 return {
36 Authorization: 'Bearer TEST_TOKEN',
37 }[name]
38 },
39 }
40
41 const res = {
42 clearCookie: jest.fn(),
43 cookie: jest.fn(),
44 end: jest.fn(),
45 locals: {
46 content: {},
47 },
48 json: jest.fn(),
49 send: jest.fn(),
50 sendStatus: jest.fn(),
51 set: jest.fn(),
52 }
53 const next = jest.fn()
54
55 return {req, res, next}
56}
57
58test('lists blog posts for the logged in user', async () => {
59 const {req, res, next} = setup()
60
61 await blogPostController.loadBlogPosts(req, res, next)
62
63 expect(res.json).toHaveBeenCalledTimes(1)
64 expect(res.json).toHaveBeenCalledWith({
65 posts: expect.arrayContaining([
66 expect.objectContaining({
67 title: 'Test Post 1',
68 subtitle: 'This is the subtitle of Test Post 1',
69 body: 'The is the body of Test Post 1',
70 }),
71 ]),
72 })
73})
74
75test('returns an empty list when there are no blog posts', async () => {
76 const {req, res, next} = setup()
77 req.user.latitude = 31.230416
78 req.user.longitude = 121.473701
79
80 await blogPostController.loadBlogPosts(req, res, next)
81
82 expect(res.json).toHaveBeenCalledTimes(1)
83 expect(res.json).toHaveBeenCalledWith({
84 posts: [],
85 })
86})

Now can you tell? What's the difference between the first and the second test? In the first our user is in London and in the second our user is in Shanghai! Gee, sure would've been nice if our co-workers had told us we were working on a location-based blogging platform (hey... now that's an interesting product idea 🤔).

By adding just a little mindful abstraction, we've been able to make it much more clear what actually matters in the difference of the inputs and outputs leading to tests which make a LOT more sense and are WAY easier to maintain.

AHA Testing with React

In a react world, I will sometimes have a renderFoo function that acts like the setup function here. Here's a simple example:

1import React from 'react'
2import {render, fireEvent} from 'react-testing-library'
3import LoginForm from '../login-form'
4
5function renderLoginForm(props) {
6 const utils = render(<LoginForm {...props} />)
7 const usernameInput = utils.getByLabelText(/username/i)
8 const passwordInput = utils.getByLabelText(/password/i)
9 const submitButton = utils.getByText(/submit/i)
10 return {
11 ...utils,
12 usernameInput,
13 passwordInput,
14 submitButton,
15 changeUsername: value => fireEvent.change(usernameInput, {target: {value}}),
16 changePassword: value => fireEvent.change(passwordInput, {target: {value}}),
17 submitForm: () => fireEvent.click(submitButton),
18 }
19}
20
21test('submit calls the submit handler', () => {
22 const handleSubmit = jest.fn()
23 const {changeUsername, changePassword, submitForm} = renderLoginForm({
24 onSubmit: handleSubmit,
25 })
26 const username = 'chucknorris'
27 const password = 'ineednopassword'
28 changeUsername(username)
29 changePassword(password)
30 submitForm()
31 expect(handleSubmit).toHaveBeenCalledTimes(1)
32 expect(handleSubmit).toHaveBeenCalledWith({username, password})
33})

Note: I would consider this pre-mature abstraction if you've only got two or three tests in the file that is using it and those tests are short. But if you've got some nuance you're testing (like error states for example), then this kind of abstraction is great.

Nesting

I'd recommend you give Avoid Nesting in Tests a read.

jest-in-case and test.each

If you're writing tests for a pure function, you're in luck because those are often the easiest to test for. You can seriously simplify your tests by using a simple abstraction that calls out VERY clearly the outputs and inputs.

For (contrived) example:

1import add from '../add'
2
3test('adds one and two to equal three', () => {
4 expect(add(1, 2)).toBe(3)
5})
6
7test('adds three and four to equal seven', () => {
8 expect(add(3, 4)).toBe(7)
9})
10
11test('adds one hundred and two to equal one hundred two', () => {
12 expect(add(100, 2)).toBe(102)
13})

That's pretty simple to follow, but it can be improved with jest-in-case:

1import cases from 'jest-in-case'
2import add from '../add'
3
4cases(
5 'add',
6 ({first, second, result}) => {
7 expect(add(first, second)).toBe(result)
8 },
9 [
10 {first: 1, second: 2, result: 3},
11 {first: 3, second: 4, result: 7},
12 {first: 100, second: 2, result: 102},
13 ],
14)

I probably wouldn't bother doing this for this simple example, but what's cool about it is that you can add more test cases very easily by simply adding more elements to that array. A good example of this concept (that actually doesn't use jest-in-case) is the rtl-css-js tests. Contributors to this codebase find it very easy to add new test cases with this structure.

This can also be applied to impure functions and modules as well, though it takes a little bit more work. (Here's a test that does this which I'm not totally proud of, but it's not too bad)

I personally prefer jest-in-case but Jest has a built-in test.each functionality that you may find useful.

Conclusion

Certainly our tests could've been improved by providing better names and/or comments as well, but our simple setup abstraction (by the way, that's called a "Test Object Factory") doesn't really need them. So my point is: it takes less work to write and maintain tests that have mindful abstractions applied to them.

I hope that's helpful! Good luck!

Discuss on TwitterEdit 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.