Outline

This is from a tweet which you can find here

Here's a quick rundown👇

AAA stands for: Arrange, Act, Assert.

This is a commonly taught structure for unit tests. This structure guides us in how to "arrange" our tests, and is generally considered to produce tests that are easier to maintain.

Each test should start with an arrange section, then the act section, and finally the assert section. Sections don't generally overlap (with few exceptions). I personally like to put whitespace between each test section.

Here's a very simple example I'll use for reference.

it('should return 5 when given 2 and 3', () => {
  let adder = new Adder();

  let sum = adder.add(2,3);

  expect(sum).toBe(5)
})

First is the arrange section.

This section is where the initial state is setup. A good unit test tests only a single state change. So we want to put our code into the initial state. That's what the arrange is for.

In the example, we arrange by creating a new Adder instance.

Next comes Act.

This is where we execute some kind of state change or computation. In our example we call the add method in the Act section.

Finally comes the assert section.

Here we assert that the resulting state, or computation is what we expect. This is where we cause the test to fail if we get an unexpected result, or pass if we get the expected result.

In the example we expect the sum to be 5.

Notice that each section is easy to identify. Whitespace helps.

This also makes tests predictable and improves readability. If every test has some uniformity like this, then dealing with any test, whether you wrote it or not, becomes easier.

Finally this lets our tests reflect how a state machine works.

Initial State -> State Transition -> Resulting State

Important points: Only 1 section of each kind. No going back and forth between Act and Assert. This is a best practice for unit tests: only 1 act and 1 assert section.

I think perhaps one of the more challenging aspects of unit tests is that they violate a lot of the unwritten rules we learn about coding in general and so we seek methods that make them less effective because it's more how we're used to coding.

Discounted Courses

Here at Thinkster, we use educational science to teach you five times faster than you would learn the same topics elsewhere. By joining as a Pro subscriber you have access to our complete library on courses on Angular, React, Vue, JavaScript, and More.

To help you get started, use this link for a discount on a monthly membership.

Or save even more with an annual membership.

 

I finished! On to the next chapter