Structure tests by the AAA pattern

One Paragraph Explainer

Our biggest testing challenge is the lack of headspace - we already have the production code keeping us super-busy. For this reason the testing code must stay dead-simple and easy to understand. When reading a test case - it shouldn’t feel like reading imperative code (loops, inheritance) rather more like HTML - a declarative experience. To achieve this, keep the AAA convention so the readers’ mind will parse the test intent effortlessly. There are some other similar formats to this pattern, like XUnit ‘Setup, Excercise, Verify, Teardown’. These are the three A:

The 1st A - Arrange: All the setup code to bring the system to the scenario the test aims to simulate. This might include instantiating the unit under test constructor, adding DB records, mocking/stubbing on objects and any other preparation code

The 2nd A - Act: Execute the unit under test. Usually 1 line of code

The 3rd A - Assert: Ensure that the received value satisfies the expectation. Usually 1 line of code

Code example: a test strcutured with the AAA pattern

  1. describe.skip('Customer classifier', () => {
  2. test('When customer spent more than 500$, should be classified as premium', () => {
  3. //Arrange
  4. const customerToClassify = {spent:505, joined: new Date(), id:1}
  5. const DBStub = sinon.stub(dataAccess, 'getCustomer')
  6. .reply({id:1, classification: 'regular'});
  7. //Act
  8. const receivedClassification = customerClassifier.classifyCustomer(customerToClassify);
  9. //Assert
  10. expect(receivedClassification).toMatch('premium');
  11. });
  12. });

Code Example – Anti Pattern: no separation, one bulk, harder to interpret

  1. test('Should be classified as premium', () => {
  2. const customerToClassify = {spent:505, joined: new Date(), id:1}
  3. const DBStub = sinon.stub(dataAccess, 'getCustomer')
  4. .reply({id:1, classification: 'regular'});
  5. const receivedClassification = customerClassifier.classifyCustomer(customerToClassify);
  6. expect(receivedClassification).toMatch('premium');
  7. });

“Include 6 parts in each test”

From the blog “30 Node.js testing best practices” by Yoni Goldberg

A test report example

“It is important for the test reader to be able to quickly determine what behavior the test is verifying”

From the book XUnit Patterns:

It is important for the test reader to be able to quickly determine what behavior the test is verifying. It can be very confusing when various behaviors of the system under test (SUT) are being invoked, some to set up the pre-test state (fixture) of the SUT, others to exercise the SUT and yet others to verify the post-test state of the SUT. Clearly identifying the four phases makes the intent of the test much easier to see.