How to disable angular2 animations for E2E protractor testing

2017-12-17

Introduction

Anyone who has ever worked with protractor/selenium should know how flaky they can be. Animations can add to this flakiness due to the page not being in the correct state that your tests require. For example if your testing a modal that opens with an animation, your E2E tests will generally not wait for the modal to appear without going onto the next step in the tests. What you usually end up with is a load of sleeps or expected conditions. Another way to get around this is to disable the animations when we are running our E2E tests. This blog outlines how to do this for Angular2.

How to disable animations?

In your app.component.ts file do the following

import {Component, OnInit} from '@angular/core';
import {environment} from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  enableAnimations: boolean;

  constructor(private initActions: InitActions) {
    this.enableAnimations = environment.enableAnimations;
  }
}

Next update your app.component.html file like so

<div [@.disabled]="enableAnimations">
  <div>
  </div>
</div>

As long as this is done on your top level component it will disable animations throughout the entire application.

You will also need a way to differentiate between your environments. For example on prod we do want animations, on develop we also want animations and finally on e2e we do not want animations. To get this to work you will need to create environment files. Angular-cli makes this super simple. The environment files are located under ./src/environments

Add a new file called environments.e2e.ts

export const environment = {
  enableAnimations: false
};

Also make sure to add the flag to the existing environment files and set it to true

Finally you will need to update your script to use the correct environment file when running you e2e tests. To do this update your package.json scripts

"e2e": "ng e2e -e e2e --port 9000 --proxy-config proxy.conf.js",

Will this disable all animations from other third party libraries

As long as they are using angular2 to generate the animations and not css then yes it will

Will this speed up my tests?

Yes very much