Test with Angular TestBed

In order to test components with Angular TestBed you need to do following:

  • prepare test environemt

beforeEach(() => {
    NgStateTestBed.setTestEnvironment(new ImmerDataStrategy());
    NgStateTestBed.strictActionsCheck = false;
    const initialState = { todos: [{...}] };
    NgStateTestBed.createActions(TodosStateActions, initialState, ['todos']);

    TestBed.configureTestingModule({
        declarations: [TodosComponent, TodoDescriptionComponent]
    });

    fixture = TestBed.createComponent(TodosComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});
  • strictActionCheck - since component template can have multiple components and we are not creating actions for each of them - we configure TestBed to not throw an error if actions for component were not found

  • createActions - creates actions for top component with initial state. All nested actions of nested components will be created automatically. tip: initialState, that top components was created with, should contain structure that matches nested component actions paths. For exmple: if your nested component actions path is @InjectStore([''${stateIndex}]) and your top component template is: <todo-description [statePath]="statePath" [stateIndex]="1"></todo-description> you need to make sure that initial state has array of todos with 2 items Also you can ovveride each action of nested components by creating custom ones by calling createActions. NgStateBed will look in list of custom actions before trying to create real ones.

and write your spec

it('should change child description on button click', () => {
    expect(fixture.nativeElement.querySelector('div.description').textContent).toEqual('test description');
    
    const button = fixture.debugElement.query(By.css('.button'));
    button.triggerEventHandler('click', null);
    
    fixture.detectChanges();
    
    expect(fixture.nativeElement.querySelector('div.description').textContent).toEqual('changed description');
});

tip: Since your components are using OnPush strategy please to rememeber:

  • To have your components extended with HasStore class

  • Have change detector ref injected into constructor with super call

  • call fixture.detectChanges each time you are interacting with UI or state

Last updated