ben tedder : code things

fixture.detectChanges() not working in Angular 4 karma tests

When testing an Angular 4 component, I was attempting to change a property on a component, and then calling fixture.detectChanges(), but it wasn't detecting!

Here's what I started with:

// not working
import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { BarChartComponent } from './bar-chart.component';

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

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

beforeEach(() => { fixture = TestBed.createComponent(BarChartComponent); component = fixture.componentInstance; fixture.detectChanges(); // initial detection });

it ('should handle no bars', () => { component.bars = []; fixture.detectChanges(); // trying to detect const convertedBars = []; expect(component.dataBars).toEqual(convertedBars); });

it ('should handle normal bars', () => { component.bars = [1,2,3]; fixture.detectChanges(); // trying to detect const convertedBars = []; expect(component.dataBars).toEqual(convertedBars); });

});

Turns out that when you call fixture.detectChanges() in the beforeEach method, it won't work. So simply removing it from there, and moving it down into each one of the tests is what fixed it for me. Check it out:

// WORKING!!
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { BarChartComponent } from './bar-chart.component';

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

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

beforeEach(() => { fixture = TestBed.createComponent(BarChartComponent); component = fixture.componentInstance; // removed initial detection });

it ('should handle no bars', () => { component.bars = []; fixture.detectChanges(); // now it detects! const convertedBars = []; expect(component.dataBars).toEqual(convertedBars); });

it ('should handle normal bars', () => { component.bars = [1,2,3]; fixture.detectChanges(); // now it detects! const convertedBars = []; expect(component.dataBars).toEqual(convertedBars); });

});

Hope it helps!