Checking the text both before and after clicking a link by using a method such as content verification

Currently, I am encountering an issue with validating the text on my links before and after they are clicked.

If the link text reads "one two" before clicking and remains as "one two" after the click, then the test case passes. However, if the text changes to "two one" after the click, the test case fails.

I have tried using

expect(beforeClick).toContain(afterClick)
and
expect(beforeClick).matches(afterClick)
, but both methods do not seem to work for me. Therefore, I am in search of a simpler method like just containing the text.

Do you know of any alternative approach that could help with this situation?

verifyLinks() {

    var allLinks = element.all(by.css('div>h3>a'));

    browser.sleep(15000); // added for debugging purposes to wait for page loading.

    allLinks.count().then(function (length) {

        console.log('Number of links: ' + length);

        for (let i = 0; i < length; i++) {


            allLinks.get(i).getText().then(function (linkTextBeforeClick) {

                var string = linkTextBeforeClick.replace(/\(|,/g, '');
                var textBeforeClick = string.replace(/\)|,/g, '');

                console.log("Before Click Text:" + textBeforeClick);
                allLinks.get(i).click();

                browser.sleep(5000);

                element(by.css('div>h2')).getText().then(function (linkTextAfterClick) {

                    var string = linkTextAfterClick.replace(/\(|,/g, '');
                    var textAfterClick = string.replace(/\)|,/g, '');

                    console.log("After Click Text:" + textAfterClick);

                    expect(textBeforeClick).toContain(textAfterClick);
                })

                browser.navigate().back();
            })

        }



    })
}

Answer №1

For those utilizing the powerful async/await method (a highly recommended practice that simplifies writing sequential tests in an asynchronous environment), the code snippet below demonstrates its application:

const link = getElement(...);

const initialText = await link.getText();

await link.click()

const newText = await link.getText();

expect(initialText).toEqual(newText);

Answer №2

checkLinks() {
  let allLinks = element.all(by.css('div>h3>a'));

  allLinks.count().then(function(count){
    console.log('Number of links:', count);

    for(let i=0;i<count;i++) {

      let beforeText = extractLinkText(allLinks.get(i));
      allLinks.get(i).click();
      browser.sleep(5000);

      let afterLink = element(by.css('div>h2'); 
      // Confirm that the locator for finding the link after click is correct.

      let afterText = extractLinkText(afterLink);

      Promise.all([beforeText, afterText])
             .then(function(txts){
               console.log('Link text before click:', txt[0]);
               console.log('Link text after click:', txt[1]);
               expect(txt[0]).toEqual(txt[1]);
             });

      browser.navigate().back();
      browser.sleep(5000);
    }
  });
}

extractLinkText(link) {
  return link.getText().then(function(str){
    return str.replace(/\(|,/g, '').replace(/\)|,/g, '').trim();
  });
}

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

Initiate asynchronous ngOnInit

Can ngOnInit() actually return a promise? I've noticed a common practice where developers use this approach and it appears to be functional. However, there is a risk with unobserved promises as they can be resolved or rejected at unexpected times, s ...

React Hook Form: Reset function triggers changes across all controllers on the page

I encountered an issue with using the reset function to clear my form. When I invoke the reset function, both of my form selects, which are wrapped by a Controller, get cleared even though I only defined default value for one of them. Is there a way to pr ...

Building an Angular CLI application with Typescript that handles multiple HTTP calls using polling through a timer

I am working with a Django backend and I need to check the status of multiple Celery Tasks () every 3 seconds. For instance, let's say I have 4 task IDs: 3099023 3493494 4309349 5498458 My goal is to make an http.get<...>(backend) call every ...

Angular8 Material Grid displaying headers and tiles, experiencing slight resizing issue with mat-grid-tile content

Exploring Angular8 Material: Grid Layout with Headers and Tiles Currently, I am delving into the workings of the grid system within Angular Material. I am dynamically fetching components and organizing them within a grid. While the grid list and tiles are ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

Will the async pipe activate onPush change detection in Angular?

I have searched various sources for the question above, but I am finding conflicting answers. For example, on Angular University's website, it is mentioned that change detection is triggered when the async pipe receives a new observable value. However ...

How can a secondary property type be determined by the key utilized in another property?

My goal is to develop a filter type that uses the primary object type to specify a set of keys for "field" and then assigns the appropriate type to the "value". However, I have encountered challenges in achieving this as the best outcome I could attain w ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

Having trouble closing my toggle and experiencing issues with the transition not functioning properly

Within my Next.js project, I have successfully implemented a custom hook and component. The functionality works smoothly as each section opens independently without interfering with others, which is great. However, there are two issues that I am facing. Fi ...

Angular application triggering multiple subscribe method calls upon a link click event

Here is the code for my navbar component: <li *ngFor="let item of menu"> <a *ngSwitchCase="'link'" routerLinkActive="active" [routerLink]="item.routerLink" (click)="Navigation(item.title)&q ...

We are unable to update the document in AngularFire as the document reference ID could not be retrieved

I am currently working on an update function that is designed to retrieve a specific document based on its unique document uid, which is connected to the authenticated user's uid. In another part of my code, I have a function that successfully fetche ...

Develop a universal function for inserting information into an array within a data set

I need assistance with my Typescript code. I am currently working on a method that pushes data into an array in a mongoose collection. However, the issue I'm facing is that the value is not being passed dynamically to the Key field in the $set operato ...

Unable to alter Mui input label color upon focus using theme.ts

In my next.js app, I'm facing an issue with changing the color of the label in a Material UI input field using Mui. Despite updating the theme.ts file to change the border bottom color and label color, only the border bottom color is being applied. T ...

When utilizing the useRef hook in Material-UI, an error may arise stating: "The property 'value' is not found on the type 'never'."

Currently, I am utilizing material UI to construct a login and registration page. In the process, I am leveraging the useRef hook to retrieve a reference instance for a TextFiled, and using xxxRef.current.value to access the input value. Despite being abl ...

The necessity for one type argument is apparent in a generic type, particularly when it is divided into a distinct type

I have a simple scenario that resembles the following and is functioning perfectly: export interface CustomState { someBool: boolean; status: string; } function checkStateDifference<K extends keyof CustomState>(props: { stateKey: K, value: Custo ...

Angular2 - error in long-stack-trace-zone.js at line 106: Zone variable is not defined

Currently, I am utilizing the Angular2 starter with webpackjs AMD. While there are no build errors showing up, I encounter some issues when browsing (using npm server), resulting in the following errors: What aspects might I be overlooking in my build con ...

Dealing with conflicting tsconfig.json files: Utilizing CommonJS for Node.js and ES6 for React.js

Here is the current folder setup for my TypeScript files: ts_dev --client *components.tsx *tsconfig.json --server *server.ts *tsconfig.json --share *utility.ts The Node.js server needs to use commonjs modules, while the client side compone ...

How can we verify if a React component successfully renders another custom component that we've created?

Consider this scenario: File ComponentA.tsx: const ComponentA = () => { return ( <> <ComponentB/> </> ) } In ComponentA.test.tsx: describe("ComponentA", () => { it("Verifies Compo ...

How can I specify the type of an object in Typescript to mirror a class's properties as a list?

This demonstration is kept simplistic and straightforward, yet the ultimate objective is far more intricate. It is crucial to grasp the method behind achieving this. Let's assume there exists a class class Foo { bar: string; baz: number; bob: a ...

Remove a record from Angular 2 Firebase collection

I've been searching extensively for a solution to this problem. Despite following the documentation on AngularFire 2 and Angular 2, I am unable to find a working answer. My goal is simply to delete a specific entry in my Firebase database using its un ...