10. Test EventListComponent

In this section we will add snapshot tests with Jest that are a very useful tool whenever you want to make sure your UI does not change unexpectedly.

1. Add a snapshot test

In this test we will first populate the attendees manually by assigning the variable to a hardcoded value in the test. We then run fixture.detectChanges which triggers Angular to run change detection and update the HTML template. Last we do a expectation using the .toMatchSnapshot Jest matcher.

  • Add a snapshot test to the EditListComponent.

  • The toMatchSnapshot matcher might cause an error with the compiler not knowing this symbol, but do not worry it will still work.

src/app/event/components/event-list/event-list.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Attendee } from './../../../models';

import { EventListComponent } from './event-list.component';

describe('EventListComponent', () => {
  let component: EventListComponent;
  let fixture: ComponentFixture<EventListComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ EventListComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EventListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should have no attendees on load', () => {
    expect(component).toMatchSnapshot();
  });

  it('should have 1 attendee on load', () => {
    component.attendees = [
      {name: 'Duncan', attending: true, guests: 2}
    ] as Attendee[];
  
    fixture.detectChanges();

    expect(component).toMatchSnapshot();
  });
});

Last updated