1

I am getting ExpressionChangedAfterItHasBeenCheckedError with a getter and BehaviorSubject (fun, right?).

Here is the code in the component

    private _windowHeight: string = '';

    constructor( private stepService: StepService, private commonService: CommonService ) {
      this.commonService.windowHeight.subscribe( ( height: number ) => {
        this._windowHeight = height + 'px';
      } );
    }

    @HostBinding( 'style.min-height' )
    public get windowHeight(): string {
      return this._windowHeight;
    }

commonService.windowHeight is a BehaviorSubject. All is fine and well when running this code in a normal browser.

My problem arises when I try to run unit tests with the component. All imports, declarations and providers are fine, and still with a simple test like this

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

it throws the Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '0px'. Current value: '865px'.

What could be the issue here? The environment: Angular 4.0.2, Angular CLI, karma, headless Chrome.

Thanks!

Maciej Treder
  • 11,866
  • 5
  • 51
  • 74
pop
  • 3,464
  • 3
  • 26
  • 43
  • do u have ngAfterViewInit or any other lifecycle methods in the component? – Julia Passynkova May 24 '17 at 13:30
  • yes, I do! basically, the behavior subject is being set with a call from ngAfterViewInit. why? – pop May 24 '17 at 13:37
  • Here is a blog post explaining the issue, might help! https://medium.com/@golbie/angular-2-change-detection-what-the-hell-is-has-changed-after-it-was-checked-82007cdfa38a – Fredrik Lundin May 24 '17 at 13:50
  • You can not change any model value in life cycle hooks that impacts a functions or attributes used in the component view. This is by angular design. Also you do not see errors when you run the app probably because you enabled prodmode? – Julia Passynkova May 24 '17 at 14:02
  • The app runs in dev mode - which makes this error even more surprising when testing. :/ Need to think about this for a while - get window height and set :host attribute to the value... – pop May 24 '17 at 14:12
  • Found this: https://stackoverflow.com/a/43833815/542191 Works for a singleton service. Let's see if it passes unit tests. – pop May 24 '17 at 14:26

0 Answers0