Menu Home

Angular unit testing: Has the correct array element been deleted?

In this post I will show you how to write an automated unit test in Angular using the Jasmine\Karma framework to assert the correct array element has been deleted.

The Unit Test will use the Arrange, Act and Assert (AAA) Pattern and to keep the post on focused on the unit test code, I do not show the component code that is under test.

TLDR;

Jump straight to Assert, this shows you how to check the array contains the elements expected.

Arrange

The first code snippet starts with the description of the test suite, Delete. The single test in the suite uses the standard naming convention so there is no ambiguity regarding what this test does. The description is read as “it should remove the second episode from the episodes array”

The component is set up for the running the test with the mock service deleteEpisode method initialised to handle the returned observable and the component’s episodes array populated.

describe('Delete', () => {        
         it('should remove the second episode from the episodes array', () => {                                    
              // Arrange
              mockEpisodeService.deleteEpisode.and.returnValue(of(true));                        
              component.episodes = EPISODES;
...    

Act

Next the component’s delete method is called with the array’s second element.

// Act
component.delete(EPISODES[1]);

Assert

The last step is to assert that the expected array element has been deleted. Using the expect’s toEqual method the array is checked to ensure it only contains the first and last elements.

 // Assert
expect(component.episodes).toEqual([EPISODES[0], EPISODES[2]]);  

Pro Tip

Test your tests.

Try your assert statement with data that you know should cause the test to fail. When putting together this example I added the deleted element to the elements being checked and saw the test fail.

Putting all this together

The complete test case looks like this.

import { of } from "rxjs";
import { EpisodesComponent } from "./episodes.component"

describe('EpisodesComponent', () => {
    let component: EpisodesComponent;
    let EPISODES;
    let mockEpisodeService;

    beforeEach(() => {
        EPISODES = [
            {id:1, name: 'Murder by the Book', season: 1},
            {id:2, name: 'Last Salute to the Commodore', season: 5},
            {id:3, name: 'An Exercise in Fatality', season: 4},
        ]

        mockEpisodeService = jasmine.createSpyObj(['deleteEpisode']);

        component = new EpisodesComponent(mockEpisodeService);
    })

    describe('Delete', () => {
        it('should remove the second episode from the episodes array', () => {            
            
            // Arrange
            mockEpisodeService.deleteEpisode.and.returnValue(of(true));            
            component.episodes = EPISODES;
            
            // Act
            component.delete(EPISODES[1]);
            
            // Assert
            expect(component.episodes).toEqual([EPISODES[0], EPISODES[2]]);  
        })       
    })
})

To run the test, from the command line type:

ng test 

For a successful test the command line will show:

Executed 1 of 1 SUCCESS (0.053 secs / 0.018 secs)
TOTAL: 1 SUCCESS

Karma displays

Acknowledgements

Thanks to Joe Eames and his excellent Plurasight course Unit Testing in Angular which was the inspiration for this post and the basis for the example used.

Categories: Angular Unit Testing

oraclefrontovik

Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.