Skip to content

Instantly share code, notes, and snippets.

@kcak11
Last active June 7, 2021 06:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kcak11/57b380aafb8b69d3c20e00b33eb29ad5 to your computer and use it in GitHub Desktop.
Save kcak11/57b380aafb8b69d3c20e00b33eb29ad5 to your computer and use it in GitHub Desktop.
Angular Screen Simulation

Angular Screen Simulation

Usually while developing / testing an Angular application, there is a need to run a particular flow to reach a specific screen and then if we want to make any code changes like CSS / TS / TEMPLATE, then again we need to go back and come from the beginning to that specific screen. This might be easier if the screen appears 2nd or 3rd in the flow, but if the screen appears at 10th position for example, then it gets difficult to complete the flow and test with all the possible combinations each time.

To address this complexity, there is an easier way to simulate the various combinations, as described below.

In the constructor of your Angular component, inject the ngZone property.

import { NgZone } from '@angular/core';
.
.
constructor(private myService: MyService, private ngZone: NgZone){}

Then inside the constructor add the below code snippet:

    let _this = this;
    (<any>window)["testComp"] = function (fn) {
        if (fn) {
            _this.ngZone.run(() => {
                fn.apply(_this, []);
            });
        }
    };

The constructor should now look something like below:

constructor(private myService: MyService, private ngZone: NgZone){
    let _this = this;
    (<any>window)["testComp"] = function (fn) {
        if (fn) {
            _this.ngZone.run(() => {
                fn.apply(_this, []);
            });
        }
    };
}

After making the above change, navigate to the specific screen in the browser and open the Developer Tools -> Console.

In the Console you can now easily simulate the various combinations for the screen via the below example code snippet:

    testComp(function () {
        this.myService.setSomething(true);
        //this.myService.setSomething(false);
        this.myService.myProp = "some value";
        //this.myService.anotherProp = "another value";
    });

Note: Arrow functions should NOT be used in the constructor or from the Developer Tools -> Console as the this context will not match with the component's this. So a regular function needs to be used instead.

Important Note:

Before committing your code to the version-control, ensure that the test code in the constructor and the associated ngZone import are removed. Leaving the test code in the constructor, would expose the testComp function to the users and that is not something we would want to happen in production.

Enjoy Developing / Testing !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment