Exploring methods for interacting with and controlling structural directives in e2e testing

Background: My goal is to permutation all potential configurations of an Angular2 screen for a specified route and capture screenshots using Protractor from the following link: http://www.protractortest.org/#/debugging.

Problem: I am struggling to figure out how to access a directive (like ng-if, for example) during an end-to-end test.

  • Is it feasible to reach the ng-if directive within an e2e test?
    • If yes: Is there a method to alter the directive? By manipulation, I mean influencing the evaluation of the directive without altering the input that the directive relies on.

Potential solution approach: presented here is an instance of how I access the router in order to navigate to a specific route:

it('should get the router', () => {
browser.executeScript(() => {
  const ng = window['ng'];
  const root = document.getElementsByTagName('app-root')[0];
  const router = ng.probe(root).injector.get(ng.coreTokens.Router);
  const routes = router.config;
  ...
  ...
  return [];
}).then(ret=> console.log(ret));
});

Considerations:

  • Perhaps it might be possible to retrieve the ng-if directives somehow using ng.probe

I would appreciate any guidance or suggestions related to my query.

Answer №1

To achieve this task, you can follow the steps below:

Here is the HTML code snippet:

<button id="search">Search for ngIf directives and display all</button>

And here is the corresponding script:


var searchComments = function(element) {
    var nodeList = [];
    for(var j = 0; j < element.childNodes.length; j++) {
        var nodeElement = element.childNodes[j];
        if(nodeElement.nodeType === 8) {
            nodeList.push(nodeElement);
        } else {
            nodeList.push.apply(nodeList, searchComments(nodeElement));
        }
    }
    return nodeList;
};


function findNgIfDirectives() {
    var comments = searchComments(document);
    const angular = window['angular'];
    comments.forEach(function(commentNode) {
        var debugElement = angular.probe(commentNode);
        var ngIfDirective = (debugElement.providerTokens[0]);
        var ngIfInstance = debugElement.injector.get(ngIfDirective);

        ngIfInstance.ngIf = true;
    });

}
document.getElementById('search').addEventListener('click', findNgIfDirectives)

Sample Plunker Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Add Multiple Components to app.module.ts in Angular-cli RC 5

I'm currently working on a project using Angular-cli RC5 and I'm facing some challenges creating charts. First, I created a new component called "chart" Then, I created a directive named "line-graph.directive.ts" This is how my folder structur ...

Angular template driven forms fail to bind to model data

In an attempt to connect the model in angular template-driven forms, I have created a model class and utilized it to fill the input field. HTML: <div class="form-group col-md-2 col-12" [class.text-danger]="nameCode.invalid && nameCode.touched ...

Using interfaces for typecasting in TypeScript

Consider the code snippet below: let x = { name: 'John', age: 30 } interface Employee { name:string, } let y:Employee = <Employee>x; console.log(y); //y still have the age property, why What is the reason for TypeScript ov ...

Adjust the appearance attribute of FormField within the designated theme

Currently, I am collaborating within an NX Monorepo and utilizing a shared ui-components library that extends the capabilities of Angular Material Components. Despite using different themes for various applications, I am aiming to incorporate appearance=&a ...

Utilizing Typescript with Angular 2 to efficiently convert JSON data into objects within HTTP requests

I am dealing with a file called location.json, which contains JSON data structured like this: { "locations": [ { "id": 1, "places": [ { "id": 1, "city": "A ...

Ensuring TypeScript's strict null check on a field within an object that is part of an

When using TypeScript and checking for null on a nullable field inside an object array (where strictNullCheck is set to true), the compiler may still raise an error saying that 'Object is possibly undefined'. Here's an example: interface IA ...

The .ts source file is mysteriously missing from the development tool's view after being deployed

When I work locally, I can see the .ts source files, but once I deploy them, they are not visible in any environment. Despite setting my sourcemap to true and configuring browserTargets for serve, it still doesn't work. Can someone help with this issu ...

What is the best way to find the average time in Typescript?

I am dealing with an object that contains the following properties: numberOfReturns: number = 0; returns_explanations: string [] = []; departure_time: string = ''; arrival_time: string = ''; The departure_time property hold ...

The function within the Context Hook has not been invoked

My attempt to implement a signin method using the context hook is not working as expected inside the AuthContext file. When calling the signin method from the Home Page, neither the console.log nor the setUser functions are being executed inside the AuthC ...

Save data to local storage when the form is submitted, retrieve it when the page is reloaded

I need help with setting form data in local storage upon form submission and displaying a message in the console if the form has already been submitted when the page is refreshed. I am struggling to write the reload condition for this functionality. Here ...

Alerts created with the AlertController in Ionic 4 Angular are not displaying the message when the

After creating a reliable alert service for my Ionic 4 project, I encountered an issue when building the release version of the app. Despite functioning perfectly in other environments like "ionic serve" and "ionic cordova emulate", the message part of the ...

Tips for setting a default value in a generic function in TypeScript, where the default argument's type is determined by the generic parameter

One of my functions calls an API and accepts a parameter to limit the fields returned by the API: type MaximumApiResponse = { fieldA: string, fieldB: number } const f = async <U extends keyof MaximumApiResponse>( entity: number, prop ...

Require that the parent FormGroup is marked as invalid unless all nested FormGroups are deemed valid - Implementing a custom

Currently, I am working on an Angular 7 project that involves dynamically generating forms. The structure consists of a parent FormGroup with nested FormGroups of different types. My goal is to have the parentForm marked as invalid until all of the nested ...

Angular Image Cropping: A How-To Guide

I have been on the lookout for an Angular plugin that allows me to crop images before uploading them to the database. Despite spending all day searching, I have not been able to find a suitable plugin that meets my requirements. What I need specifically i ...

Is there a way to define an interface that consists of child objects as the type for a function that uses destructured props?

Is there an alternative to this method? import { client } from "./setupApi"; export const getLayout = ({ page, entity, list }: {page: string, entity: string, list: string}) => { return client.get("/secure/nav.json"); }; How do I ...

Tips for constructing node.js projects using local versions of the dependencies?

Recently, I've been tackling a rather intricate node.js project (find it at https://github.com/edrlab/thorium-reader/) while trying to incorporate local versions of certain dependencies. Surprisingly, I can successfully build and execute the project ...

Unable to circumvent the Angular sanitize security measures

Using a wysiwyg editor (angular-editor): <angular-editor [(ngModel)]="code" name="code"></angular-editor> Underneath the editor, attempting to implement ngx-highlightjs: <pre> <code [highlight]="code" [lineNumbers]="true"></ ...

How can one change the data type specified in an interface in TypeScript?

I am currently diving into TypeScript and looking to integrate it into my React Native application. Imagine having a component structured like this: interface Props { name: string; onChangeText: (args: { name: string; value: string }) => void; s ...

Issue encountered in event.d.ts file at line 74, character 76: TypeScript error TS2370: A rest parameter is required to be an array type

I am currently working on a project in Angular 6 and I encountered an issue while trying to integrate Google Maps into my website. When running ng serve, I received the following errors: ERROR in node_modules/@types/googlemaps/reference/event.d.ts(74,76): ...

What is the recommended Firefox version that works seamlessly with Selenium Webdriver 3.6.0?

My current automation setup involves using Protractor with VS Code as my IDE. While I've successfully run my scripts on Chrome, I'm experiencing failures when attempting to run them on Firefox. It appears to be a compatibility issue. Can anyone p ...