This site runs best with JavaScript enabled.

Static vs Unit vs Integration vs E2E Testing for Frontend Apps

January 28, 2019

Video Blogger

Screenshot from TestingJavaScript.com


What these mean, why they matter, and why they don't

In my interview "Testing Practices with J.B. Rainsberger" available on TestingJavaScript.com he gave me a metaphor I really like. He said:

You can throw paint against the wall and eventually you might get most of the wall, but until you go up to the wall with a brush, you'll never get the corners. πŸ–ŒοΈ

I love that metaphor in how it applies to testing because it's basically saying that choosing the right testing strategy is the same kind of choice you'd make when choosing a brush for painting a wall. Would you use a fine-point brush for the entire wall? Of course not. That would take too long and the end result would probably not look very even. Would you use a roller to paint everything, including around the mounted furnishings your great-great-grandmother brought over the ocean a hundred years ago? No way. There are different brushes for different use cases and the same thing applies to tests.

Nearly 1 year ago, created the Testing Trophy. Since then Maggie Appleton (the mastermind behind egghead.io's masterful art/design) created this for TestingJavaScript.com:

The Testing Trophy

In the Testing Trophy, there are 4 types of tests. It shows this text above, but for the sake of those using assistive technologies (and in case the image fails to load for you), I'll write out what it says here from top to bottom:

  • End to End: A helper robot that behaves like a user to click around the app and verify that it functions correctly. Sometimes called "functional testing" or e2e.
  • Integration: Verify that several units work together in harmony.
  • Unit: Verify that individual, isolated parts work as expected.
  • Static: Catch typos and type errors as you write the code.

The size of these forms of testing on the trophy is relative to the amount of focus you should give them when testing your applications (in general). I want to take a deep dive on these different forms of testing, what it means practically, and what we can do to optimize for the greatest bang for our testing buck.

Test Types

Let's look at a few examples of what these kinds of tests are

End to End

Typically these will run the entire application (both frontend and backend) and your test will interact with the app just like a typical user would. These tests are written with cypress.

1import {generate} from 'todo-test-utils'
2
3describe('todo app', () => {
4 it('should work for a typical user', () => {
5 const user = generate.user()
6 const todo = generate.todo()
7 // here we're going through the registration process.
8 // I'll typically only have one e2e test that does this.
9 // the rest of the tests will hit the same endpoint
10 // that the app does so we can skip navigating through that experience.
11 cy.visitApp()
12 .getByText(/register/i)
13 .click()
14 .getByLabelText(/username/)
15 .type(user.username)
16 .getByLabelText(/password/)
17 .type(user.password)
18 .getByText(/login/i)
19 .click()
20 .getByLabelText(/add todo/i)
21 .type(todo.description)
22 .type('{enter}')
23 .getByTestId('todo-0')
24 .should('have.value', todo.description)
25 .getByLabelText('complete')
26 .click()
27 .getByTestId('todo-0')
28 .should('have.class', 'complete')
29 // etc...
30 // My E2E tests typically behave similar to how a user would.
31 // They can sometimes be quite long.
32 })
33})

Integration

The test below renders the full app. This is NOT a requirement of integration tests and most of my integration tests don't render the full app. They will however render with all the providers used in my app (that's what the render method from the imaginary "til-client-test-utils" module does). The idea behind integration tests is to mock as little as possible. I pretty much only mock:

  1. Network requests (see axiosMock)
  2. Components responsible for animation (because who wants to wait for that in your tests?)
1import React from 'react'
2// this module is mocked via jest's __mocks__ directory feature
3import axiosMock from 'axios'
4import {render, generate, fireEvent} from 'til-client-test-utils'
5import {init as initAPI} from '../utils/api'
6import App from '../app'
7
8beforeEach(() => {
9 window.localStorage.removeItem('token')
10 axiosMock.__mock.reset()
11 initAPI()
12})
13
14test('login as an existing user', async () => {
15 const {
16 getByTestId,
17 container,
18 getByText,
19 getByLabelText,
20 finishLoading,
21 } = render(<App />)
22
23 // wait for the app to finish loading the mocked requests
24 await finishLoading()
25
26 fireEvent.click(getByText(/login/i))
27 expect(window.location.href).toContain('login')
28
29 // fill out form
30 const fakeUser = generate.loginForm()
31 const usernameNode = getByLabelText(/username/i)
32 const passwordNode = getByLabelText(/password/i)
33 usernameNode.value = fakeUser.username
34 passwordNode.value = fakeUser.password
35
36 // submit form
37 const {post} = axiosMock.__mock.instance
38 const token = generate.token(fakeUser)
39 post.mockImplementationOnce(() =>
40 Promise.resolve({
41 data: {user: {...fakeUser, token}},
42 }),
43 )
44 fireEvent.click(getByText(/submit/i))
45
46 // wait for the mocked requests to finish
47 await finishLoading()
48
49 // assert calls
50 expect(axiosMock.__mock.instance.post).toHaveBeenCalledTimes(1)
51 expect(axiosMock.__mock.instance.post).toHaveBeenCalledWith(
52 '/auth/login',
53 fakeUser,
54 )
55
56 // assert the state of the world
57 expect(window.localStorage.getItem('token')).toBe(token)
58 expect(window.location.href).not.toContain('login')
59 expect(getByTestId('username-display').textContent).toEqual(fakeUser.username)
60 expect(getByText(/logout/i)).toBeTruthy()
61})

Unit

1import 'react-testing-library/cleanup-after-each'
2import 'jest-dom/extend-expect'
3import React from 'react'
4import {render} from 'react-testing-library'
5import ItemList from '../item-list'
6
7// Some people don't call these a unit test because we're render to the DOM with React.
8// They'd tell you to use shallow rendering instead.
9// When they tell you this, send them to https://kcd.im/shallow
10test('renders "no items" when the item list is empty', () => {
11 const {getByText} = render(<ItemList items={[]} />)
12 expect(getByText(/no items/i)).toBeInTheDocument()
13})
14
15test('renders the items in a list', () => {
16 const {getByText, queryByText} = render(
17 <ItemList items={['apple', 'orange', 'pear']} />,
18 )
19 // note: with something so simple I might consider using a snapshot instead, but only if:
20 // 1. the snapshot is small
21 // 2. we use toMatchInlineSnapshot()
22 expect(getByText(/apple/i)).toBeInTheDocument()
23 expect(getByText(/orange/i)).toBeInTheDocument()
24 expect(getByText(/pear/i)).toBeInTheDocument()
25 expect(queryByText(/no items/i)).not.toBeInTheDocument()
26})

Everyone calls this a unit test and they're right:

1// pure functions are the BEST for unit testing and I LOVE using jest-in-case for them!
2import cases from 'jest-in-case'
3import fizzbuzz from '../fizzbuzz'
4
5cases(
6 'fizzbuzz',
7 ({input, output}) => expect(fizzbuzz(input)).toBe(output),
8 [
9 [1, '1'],
10 [2, '2'],
11 [3, 'Fizz'],
12 [5, 'Buzz'],
13 [9, 'Fizz'],
14 [15, 'FizzBuzz'],
15 [16, '16'],
16 ].map(([input, output]) => ({title: `${input} => ${output}`, input, output})),
17)

Static

1// can you spot the bug?
2// I'll bet ESLint's for-direction rule could
3// catch it faster than you in a code review πŸ˜‰
4for (var i = 0; i < 10; i--) {
5 console.log(i)
6}
7
8const two = '2'
9// ok, this one's contrived a bit,
10// but TypeScript will tell you this is bad:
11const result = add(1, two)

Why do we test again?

I think it's important to remember why it is that we write tests in the first place. Why do you write tests? Is it because I told you to? Is it because your PR will get rejected unless it includes tests? Is it because testing enhances your workflow?

The biggest and most important reason that I write tests is CONFIDENCE. I want to be confident that the code I'm writing for the future wont break the app that I have running in production today. So whatever I do, I want to make sure that the kinds of tests I write bring me the most confidence possible and I need to be cognizant of the trade-offs I'm making when testing.

Let's talk trade-offs

There are some important elements to the testing trophy I want to call out in this picture (ripped from my slides):

The Testing Trophy with arrows indicating the trade-offs

The arrows on the image signify three trade-offs you make when writing automated tests:

Cost: οΏ  heap ➑ πŸ’°πŸ€‘πŸ’°

As you move up the testing trophy, the tests become more costly. This comes in the form of actual money to run the tests in a continuous integration environment, but also in the time it takes engineers to write and maintain each individual test.

The higher up the trophy you go, the more points of failure there are and therefore the more likely it is that a test will break, leading to more time needed to analyze and fix the tests. Keep this in mind because it's important #foreshadowing...

Speed: πŸŽπŸ’¨ ➑ 🐒

As you move up the testing trophy, the tests typically run slower. This is due to the fact that the higher you are on the testing trophy, the more code your test is running. Unit tests typically test something small that has no dependencies or will mock those dependencies (effectively swapping what could be thousands of lines of code with only a few). Keep this in mind because it's important #foreshadowing...

Confidence: Simple problems πŸ‘Œ ➑ Big problems πŸ˜–

The cost and speed trade-offs are typically referenced when people talk about the testing pyramid πŸ”Ί. If those were the only trade-offs though, then I would focus 100% of my efforts on unit tests and totally ignore any other form of testing when regarding the testing pyramid. Of course we shouldn't do that and this is because of one super important principle that you've probably heard me say before:

The more your tests resemble the way your software is used, the more confidence they can give you.

What does this mean? It means that there's no better way to ensure that your Aunt Marie will be able to file her taxes using your tax software than actually having her do it. But we don't want to wait on Aunt Marie to find our bugs for us right? It would take too long and she'd probably miss some features that we should probably be testing. Compound that with the fact that we're regularly releasing updates to our software there's no way any amount of humans would be able to keep up.

So what do we do? We make trade-offs. And how do we do that? We write software that tests our software. And the trade-off we're always making when we do that is now our tests don't resemble the way our software is used as reliably as when we had Aunt Marie testing our software. But we do it because we solve real problems we had with that approach. And that's what we're doing at every level of the testing trophy.

As you move up the testing trophy, you're increasing what I call the "confidence coefficient." This is the relative confidence that each test can get you at that level. You can imagine that above the trophy is manual testing. That would get you really great confidence from those tests, but the tests would be really expensive and slow.

Earlier I told you to remember two things:

  • The higher up the trophy you go, the more points of failure there are and therefore the more likely it is that a test will break
  • Unit tests typically test something small that has no dependencies or will mock those dependencies (effectively swapping what could be thousands of lines of code with only a few).

What those are saying is that the lower the trophy you are, the less code your tests are testing. If you're operating at a low level you need more tests to cover the same number of lines of code in your application as a single test could higher up the trophy. In fact, as you go lower down the testing trophy, there are some things that are impossible to test.

In particular, static analysis tools are incapable of giving you confidence in your business logic. Unit tests are incapable of ensuring that when you call into a dependency that you're calling it appropriately (though you can make assertions on how it's being called, you can't ensure that it's being called properly with a unit test). UI Integration tests are incapable of ensuring that you're passing the right data to your backend and that you respond to and parse errors correctly. End to End tests are pretty darn capable, but typically you'll run these in a non-production environment (production-like, but not production) to trade-off that confidence for practicality.

Let's go the other way now. At the top of the testing trophy, if you try to use an E2E test to check that typing in a certain field and clicking the submit button for an edge case in the integration between the form and the URL generator, you're doing a lot of setup work by running the entire application (backend included). That might be more suitable for an integration test. If you try to use an integration test to hit an edge case for the coupon code calculator, you're likely doing a fair amount of work in your setup function to make sure you can render the components that use the coupon code calculator and you could cover that edge case better in a unit test. If you try to use a unit test to verify what happens when you call your add function with a string instead of a number you could be much better served using a static type checking tool like TypeScript.

Conclusion

Every level comes with its own trade-offs. An E2E test has more points of failure making it often harder to track down what code caused the breakage, but it also means that your test is giving you more confidence. This is especially useful if you don't have as much time to write tests. I'd rather have the confidence and be faced with tracking down why it's failing, than not having caught the problem via a test in the first place.

In the end I don't really care about the distinctions. If you want to call my unit tests integration tests or even E2E tests (as some people have πŸ€·β€β™‚οΈ) then so be it. What I'm interested in is whether I'm confident that when I ship my changes, my code satisfies the business requirements and I'll use a mix of the different testing strategies to accomplish that goal.

Good luck!


Learn more about Testing from me:

Here are a few relevant blog posts for you as well:

Things to not miss:

Share article