Typescript excels at gracefully handling cases where an element is not found

While working with Typescript-Protractor Jasmine, I encountered an issue where the test case (the 'it' block) is not failing when an element is not found. Instead, it shows an UnhandledPromiseRejectionWarning but still marks the script as passed.

   await element(by.xpath("xpath")).click().then(()=>{logObj.info("clicked")});

Answer №1

When handling such cases, it is important to work with expectations (assertions). Just because a click or other action is not successful does not necessarily mean the test should fail. It is crucial to define when the test should fail.

For instance:

it('should perform a smart action', async (done) => {
    await element(by.xpath('dsadadada')).click()
        .then(() => {
            logObj.info("clicked");
        })
        .catch(rejected => {
            logObj.info("the click was unsuccessful due to rejected promise");
            done.fail(rejected); // indicate test failure
        });

    done();
});

Alternatively, you can use exception handling with 'try catch':

   it('should perform a smart action', async (done) => {

        try {
            await element(by.xpath('dsadadada')).click(); // will throw an error if not clickable
            await element(by.xpath('dsadadada')).sendKeys('dasdada'); // will throw an error if unable to send keys

        } catch (e) {
            done.fail(e); // test will fail if any action throws an error
        }

        done(); // test will be marked as success if no errors occur
    });

or use expectations:

it('should perform a smart action', async (done) => {

        await element(by.xpath('dsadadada')).click(); // will throw an error if not clickable
        expect(element(by.xpath('some new element on the page after click')).isPresent()).toBeTruthy();
        done();
    });

Example of encapsulated Page Object Model (POM):

public class PageObjectClass {
        // method for clicking x button
        public async clickOnXBtn() {
            await await element(by.xpath('dsadadada')).click();
        }
    }

    it('perform a dummy action', async (done) => {
        try {
            // pageobject is a class that contains the actions for this button.
            const pageObject = new PageObjectClass();

            await pageObject.clickOnXBtn();
        } catch (e) {
            done.fail(e);
        }

    });

More information on POM can be found here: https://github.com/angular/protractor/blob/master/docs/page-objects.md

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

Error: inability to execute performanceMeasurement.startMeasurement due to its absence in the function definition

An error occurred when attempting to login using @azure/msal-react in Next 13. Upon checking the error log, it was found that the error originated from the core library @azure/msal-react. Even after trying with a login popup, the error persisted. In my co ...

Having trouble resolving parameters? Facing an Angular dependency injection problem while exporting shared services?

Seeking to streamline the process of importing services into Angular 4 components, I devised a solution like this: import * as UtilityService from '../../services/utility.service'; As opposed to individually importing each service like so: imp ...

Tips to avoid multiple HTTP requests being sent simultaneously

I have a collection of objects that requires triggering asynchronous requests for each object. However, I want to limit the number of simultaneous requests running at once. Additionally, it would be beneficial to have a single point of synchronization afte ...

Accessing the form element in the HTML outside of the form tag in Angular 2

I am attempting to achieve the following: <span *ngIf="heroForm?.dirty"> FOO </span> <form *ngIf="active" (ngSubmit)="onSubmit()" #heroForm="ngForm"> <div class="form-group"> <label for="name">Name</label& ...

Issue with Material UI: Unable to utilize import statement outside of a module due to Select dependency

Hello there! Here is my query: I am currently working on a project using NextJS + React with node. Everything seems to be running smoothly, except for one issue I encounter when reloading a page with a Select component from Material UI. The relevant code ...

How can an array be generated functionally using properties from an array of objects?

Here's the current implementation that is functioning as expected: let newList: any[] = []; for (let stuff of this.Stuff) { newList = newList.concat(stuff.food); } The "Stuff" array consists of objects where each ...

What is the best way to create a React component that renders a class component as a functional component?

My Objective: At the moment, I am in the process of developing an AuthUserRole HOC component to manage user roles like Manager and Employee. However, I encountered a tutorial that uses a functional component to return a class component as referenced here. ...

Exploring the potential of AssemblyScript in creating immersive WebXR

I have been exploring three.js and webXR for some time now, and I wanted to incorporate it into assembly script. While I know how to make webXR work in TypeScript, I encounter an error when trying to use it in assembly script with the import statement. Her ...

Tips for refreshing the appearance of a window in angular when it is resized

I have a chat feature integrated into my application. I am looking to dynamically resize an image within the chat window when the width of the window falls below a certain threshold. Is there a method available to modify the CSS style or class based on the ...

"The debate over using 'stringly typed' functions, having numerous redundant functions, or utilizing TypeScript's string enums continues to divide the programming

I have a specific object structure that contains information about countries and their respective cities: const geo = { europe: { germany: ['berlin', 'hamburg', 'cologne'], france: ['toulouse', ' ...

Using the input type 'number' will result in null values instead of characters

My goal is to validate a number input field using Angular2: <input type="number" class="form-control" name="foo" id="foo" [min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo"> In Chrome, everything works perfectly because it ignores ...

Utilizing Visual Studio Code for setting breakpoints in Typescript Jasmine tests

Currently, I am in the process of configuring a launch setup in Visual Studio Code for debugging my unit tests. The unit tests are written in Typescript, and both the tests and the corresponding code are compiled into a single js file with a source map. ...

What is the most reliable way to create an array ensuring that all potential values come from a specific dictionary?

I am seeking a method to define the testArray so that only keys from the example dictionary can be inserted into the array. enum example { key1 = 'A', key2 = 2, key3 = '3', }; const testArray: ?? = [example.key1, example.ke ...

Encountering an Issue: Jasmine Test for Controller Availability is Unsuccessful

Here is a basic controller snippet: app.controller("RegisterController", function ($scope, $location) { // Do something }); All I am attempting to do is verify that this controller is defined: describe('RegisterController', function() { ...

Creating number inputs in Ionic 2/3 using alerts

I am currently working with Ionic 3.x on my macOS system. The issue I am facing is as follows: I have an array that contains a number and another array consisting of names. table: { number: number, names: string[] } = { number: 0, names: ['& ...

Displaying messages in an Angular 2 chatbox from the bottom to the top

As a newcomer to using typescript, I am currently working on an angular 2 project and facing some challenges with creating a chatbox. My goal is to have new messages displayed at the bottom while pushing the old ones up one line at a time, as shown in this ...

Executing Promises in TypeScript Sequentially

I have a collection of doc objects and I need to send an API request for each doc id in the list, executing the requests in a sequential manner. In my Typescript code, I am using Promise.all and Promise.allSelected to achieve this. [ { "doc_id&q ...

Issue encountered with Firebase JS SDK: firebase.d.ts file is missing which leads to a Typescript error when trying to

I'm currently working on an Ionic project with AngularFire. I encountered a typescript error when trying to run ionic cordova build --prod --release android. typescript error '/home/sebinbenjamin/workspace/myapp/node_modules/firebase/firebase. ...

Error in Typescript SPFx: The property 'news' is not found in the type 'Readonly<{}>'

Currently, I am working on developing a spfx react component to showcase an RSS feed in the browser. My prototype is functional in a test environment, however, as spfx utilizes TypeScript, I am encountering a type error that I am unsure how to resolve. Rs ...

Error encountered in azure devops preventing successful execution: "npm ERR! code ELIFECYCLE"

I am facing an issue with my Azure DevOps build pipeline that contains 2 npm tasks: - one for npm install - and the other for npm run-script build Unfortunately, I am encountering errors that do not provide sufficient information about the root cause of ...