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

What methods can be used to obtain download statistics for an Angular2 npm package?

Currently working on a presentation for an upcoming conference and faced with a bit of confusion... I'm having trouble locating the download statistics for the angular2 npm package! I've been looking here but unfortunately, there doesn't se ...

Developing a collection of components with customizable color variations using React

I am interested in creating a React component library where users can specify color variants. For instance, I want to use the following syntax: const customTheme = createCustomTheme({ button: { variants: { primary: 'primary ...

The node command line does not recognize the term 'require'

My Typescript project was compiling and running smoothly until recently when I started encountering the error ReferenceError: require is not defined every time I try to run node. I am uncertain whether this issue stems from Typescript, as even when I ru ...

A guide to implementing unit tests for Angular directives with the Jest testing framework

I am currently integrating jest for unit testing in my Angular project and I am relatively new to using jest for unit tests. Below is the code snippet for DragDropDirective: @HostListener('dragenter',['$event']) @HostListener(& ...

Convert a file into an empty array when sending a post request from Angular to Laravel

I am currently working on a simple Laravel 5 post request that aims to achieve the following tasks: Save some data to a database. Store a file (image) in public storage with a name consisting of 20 random numbers followed by '.jpg'. Save a URL ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

Difficulty encountered when attempting to create a lambda function in TypeScript

I'm having trouble understanding the following lambda function definition in TypeScript. It could be a beginner question. type P = { id: string } type F = <T>(x: T) => string const f: F = (x: P) => x.id f({ id: 'abc' } However, ...

Leveraging Angular 4 for efficient integration and application of d3 and d3-cloud libraries along with their corresponding typings

My goal is to create a word cloud using d3 + d3-cloud in Angular CLI (Angular 4+) I installed both libraries and their typings using npm i: "dependencies": { "d3": "^4.10.2", "d3-cloud": "^1.2.4" }, "devDependencies": { "@types/d3": "^4.1 ...

Steps to converting an enum or literal

Hey there, I'm relatively new to working with TypeScript and I've been experimenting with transforming enums/literals using functions. For instance, creating a capitalize function that capitalizes the first letter of a string. (e.g., mapping typ ...

Guide to implementing Google Adsense on a page post-load using Angular 6

Hi there, I recently completed my website www.revlproject.org and now I'm trying to get approved for Google Adsense. However, I keep receiving the message "valuable inventory: no content." After some investigation, I realized that because my site is b ...

How is it possible for the igx-expansion-panel to close when there is a nested angular accordion present?

Currently, I am faced with the challenge of closing the igx-expansion-panel within my Angular project. While everything functions smoothly with a standard panel, things get a bit tricky when dealing with nested angular accordion structures using igx-accord ...

Ways to narrow down const types

For the given scenario, I aim to enforce a specific format [string, number] for all function returns, while allowing varying input arguments for these functions. Access the Playground here type ReturnFormat = [string, number] type Fn = (...args: any[]) =& ...

Issue with minifying AngularJS and TypeScript route configuration for safe minification

Currently, I have a package containing multiple js files that were created from typescript files. However, when I attempt to apply minification to the package, the webpage encounters errors. The error message displayed on the Chrome console is: Uncaug ...

Creating a TypeScript class that includes all the attributes of a pre-existing object type

One technique I frequently use in TypeScript involves transforming a plain JSON object definition into a class during runtime. Here's an example: export type LessonDef = { id: string title: string slug: string shortdesc: string explanation: ...

Utilizing Async/Await to Streamline Google Maps Elevation Requests

I'm struggling to run this in a sequential manner. I've experimented with various methods like using Promise.all and getting stuck in callback hell, but what I really need is to obtain elevations for each point that has a valid altitude value (no ...

Setting a date in Angular Material 2 without closing the mdMenu

I am trying to interact with Material 2's menu. Is there a way to select a menu item without closing the menu popup? Check out this link for more information. ...

Angular can display text on hover based on the state shown in a <td> element

Working on an Angular 7 project, I have a <td> element where I display different colors to indicate the status of a task: Red - Indicates 'Delayed' Orange - Indicates 'In progress' Grey - Indicates 'Rejected' Cu ...

Establishing the rotation attribute of an SVG circle to create an angular progress tracker

Exploring the code of an Angular component and came across how the r attribute for an svg circle is defined like this: [attr.r]="radius - stroke / 2" This seems to work, but I'm wondering why it's done this way. Isn't the r attribute suppo ...

Utilizing constants within if statements in JavaScript/TypeScript

When working with PHP, it is common practice to declare variables inside if statement parenthesis like so: if ($myvar = myfunction()) { // perform actions using $myvar } Is there an equivalent approach in JavaScript or TypeScript?: if (const myvar = myf ...

The Angular client fails to receive data when the SignalR Core Hub method is called from the Controller

Issue with Angular SignalR Client not Receiving Data from ASP.NET API I have a setup where an angular website is connected to an asp.net back-end using SignalR for real-time data service. Everything was working fine when tested in localhost, but after pub ...