AAA (Arrange, Act and Assert)

The AAA pattern advocates for splitting each test into three parts: arrange, act and assert. This pattern provides a simple and uniform structure for all the tests in the set. This uniformity is one of the main advantages of this pattern: once you get used to it, you can easily read and understand any test. That, in turn, reduces maintenance costs for the entire test suite.

it('GridExControlBaseComponent should call loadData when dirtyColumns property is true, and sets dirtyColumns to false', () => {
    //Arrange
    const loadData = jest.spyOn(component, 'loadColumns');
    component.model.DirtyColumns = true;
    
    //Act
    component.detectChanges();
    component.ngDoCheck();

    //Assert
    expect(loadData).toHaveBeenCalled();
    expect(component.dirtyColumns).toBeFalsy();
  });

Arrange

The system under test and its dependencies are brought to a desired state. This section is usually the largest of the three and can be as large as the Act and Assert sections combined. But if it gets significantly larger than that, it is best to extract the arrays into private methods within the test class itself or in a separate factory class. Two popular patterns can help you reuse code from arrange sections: Object Mother and Test Data Builder.

Act

In the act section, the methods of the component under test are called, the prepared dependencies are passed and the output value (if any) is captured.

The act section is normally a single line of code, if it is more than one line it must be justified that it is needed to be able to test the objective of the test, it is always important to verify that two different things are not being tested in the same test, if so it must be separated.

Assert

In the assert section, the result is checked. The result can be represented by the return value, the final state of the test system and its contributors, or the methods that the test system called on those contributors.

A unit test is a unit of behavior, not a unit of code. A single unit of behavior can exhibit multiple results, and it is fine to evaluate them all in one test. That said, beware of overgrown assertion sections: it could be a sign of a missing abstraction in the production code.

Benefits

  1. Improved readability.

  2. Easier maintenance.

  3. Simpler testing.

  4. Allow to be able to identify errors.

  5. Works the same if you want to use BDD or TDD.

Last updated