Angular 4 + Jasmine Unit Tests: reasons why fixture.detectChanges () may not work when changing @Input () variables

He dealt with this problem and studied on the Internet information about fixture.detectChanges (), where he does not recognize changes in @Input () when explicitly inserting dummy data. There are tons of threads and documents that describe the setup, but it’s not necessary why this will disrupt all my tests.

Error: ExpressionChangedAfterItHasBeenCheckedError: The expression changed after checking it.

Removing fixture.detectChanges () seems to "resolve" this error. But now the insertion of any new dummy data (according to the specification) is not detected.

Example:

TestComponent.ts

import { TestComponent } from './test-component';
import { TestComponentModule } from './test-component.module';
import { Data } from './interfaces/data';

export class TestComponent {
    @Input() data: Data;

    displayData(){ 
        let firstName = data.first;
        let lastName = data.last;
        let fullName = firstName + ' ' + lastName;
        return fullName;
    };
}

TestComponent.spec.ts

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TestComponent } from './test-component';
import { TestComponentModule } from './test-component.module';

class DataMock {
    data: Data = getDataMock({
        first: 'Roger',
        last: 'Moore'
    });
};

describe('TestComponent', () => {
    'use strict';
    let testComponent: TestComponent;
    let fixture: ComponentFixture<TestComponent>;

    beforeEach(async() => {
        TestBed.configureTestingModule({
        imports: [ TestComponentModule ]
        }).compileComponents();
        fixture = TestBed.createComponent(TestComponent);
        testComponent = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should render the app', () => {
        expect(TestComponent).toBeDefined();
    });

    describe('displayData()', () => {
        let dataMock = new DataMock;
        beforeEach(() => {
            testComponent.data = dataMock.data;
        });

        it('should return fullName', () => {
            expect(TestComponent.displayData()).toBe('Roger Moore');
        });
    });
});
  • dataMock const - fixture.detectChanges() , .
  • dataMock - Input() fixture.detectChanges(), ,

, dataMock fixture.detectChanges()? ?

+5
1

compileComponents.

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

beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    testComponent = fixture.componentInstance;
    fixture.detectChanges();
});
0

Source: https://habr.com/ru/post/1683478/


All Articles