End-to-end testing with Protractor: Logging in page

I'm currently exploring protractor e2e testing for my ionic app to test the login page. This is my first venture into using protractor, and I'm encountering difficulties interpreting the error message that keeps popping up.

Error:- Failed: no such element: Unable to locate element: {"method":"css selector","selector":"*[id="user1"]"}

Feeling stuck and in need of some guidance as a newbie in the testing realm.

app.e2e-spec.ts:

describe('Login tests', () => {

browser.driver.get('http://url.path/login');


it('login page works', function() {
  // Checking the current url
  var currentUrl = browser.driver.getCurrentUrl();
  expect(currentUrl).toMatch('/login');
});

it('should sign in', function() {


// Locating page elements
 var userNameField = browser.driver.findElement(by.id('username'));

 var userPassField = browser.driver.findElement(by.id('password'));

userNameField.sendKeys('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d9b7b0bab299bcb4b8b0b5f7bab6b4">[email protected]</a>');
userPassField.sendKeys('123456');

return browser.driver.wait(function() {
      return browser.driver.getCurrentUrl().then(function(url) {
          return /success/.test(url);
      });
}, 10000);
});
});

Login.html:

<!--
  Custom template for the LoginPage page.

  Referencing font styles and design elements.
-->
<link href="https://fonts.googleapis.com/css?family=Sacramento" type="text/css" rel="stylesheet">

<ion-header>

    <ion-navbar transparent>
        <ion-title align="center">Atelier</ion-title>
    </ion-navbar>

  </ion-header>


  <ion-content padding>

    <div class="align">
        <h1>Atelier</h1>
    </div>

      <ion-card>
          <ion-card-header>
           Login
          </ion-card-header>
          <ion-card-content>
             <ion-list >
               <ion-item>  
                   <ion-input id="username" type="email" placeholder="Email" [(ngModel)]="user.email"></ion-input>
               </ion-item>
               <ion-item>  
                   <ion-input id="password" type="password" placeholder="Password" [(ngModel)]="user.password"></ion-input>
               </ion-item>
              <button ion-button full clear color="light" (click)="login(user)">Login</button>
              <button ion-button block round outline color="light" (click)="register()">Register</button>
             </ion-list>    
          </ion-card-content>
        </ion-card>

  </ion-content>

    <style>
      h1{
        font-size: 3em;
        text-align: center;
        font-family: Sacramento;
        font-style: cursive;
        color: white;
        text-shadow: 4px 4px 4px rgba(0,0,0,0.1); 
      }
    </style>

app.po.ts:

import { browser, by, element } from 'protractor';

export class LoginPage {
 navigateTo(){
  return browser.get('/login');
 }
 get usernameLabel() {
  return element(by.css('.login-field:nth-child(1) label'));
  }

 getEmailTextbox() {
  return element(by.id('username'));
 }
 get passwordLabel() {
  return element(by.css('.login-field:nth-child(2) label'));
  }
getPasswordTextbox() {
 return element(by.id('password'));
  }
  }

   export class Page {

   navigateTo(){
    return browser.get('/login');
      }

    getTitle() {
   return browser.getTitle();
    }

   getPageOneTitleText() {
   return element(by.tagName('page-page1')).element(by.tagName('ion- title')).element(by.css('.toolbar-title')).getText();
     }

  goToLoginPage(): any{
   let LoginPage = require("../src/pages/login/login").default;
   return new LoginPage();
  }

 getUser(){
   return element(by.id('username'))
 }

  getPass(){
   return element(by.id('password'))
   }

 }

Answer №1

If you encounter this error while using Protractor

Error: Failed - no such element found: Unable to locate element: {"method":"css selector","selector":"*[id="user1"]"}

and you are trying to use the locator with id= username, but Protractor is returning "selector":"*[id="user1"]" which seems inaccurate.

 var userNameField = browser.driver.findElement(by.id('username'));

 var userPassField = browser.driver.findElement(by.id('password'));

When using Protractor, make sure to utilize Protractor locators provided by the awesome locator class for better accuracy.

You can try using element(by.model('user.email')) as it is more suitable for your test scenario.

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

Deactivate the button until the input meets validation criteria using Angular

What I'm trying to achieve is to restrict certain input fields to only accept integer or decimal values. Here's the code snippet that I currently have: <input type="text" pattern="[0-9]*" [(ngModel)]="myValue" pInputText class="medium-field" ...

Switching cell icon when clicked - A step-by-step guide

I have a situation in ag-grid where I need to update the icon of a button in a cell when it is clicked to indicate progress and then revert back to its original state upon completion of the action. Below is the code snippet: my-custom.component.ts < ...

Step-by-step guide to minify Typescript files with Webpack

I am facing an issue in my webpack configuration while trying to minify the output bundle when working with TypeScript. Currently, only one file has been migrated to TypeScript in my project and it works fine with babel-node and the dev bundle without Ugli ...

"Encountered an error: 'Unexpected token export' while working on an Angular application using SystemJS and

Inquiry: perplexing "Unexpected token export" Recently encountered this issue in an Angular demo hosted on plunker where SystemJS is used to transpile TypeScript code directly in the browser. The code was flawless and operated smoothly on my local syste ...

Encountering subscription API issues from MongoDB following a route modification

I developed a service to retrieve data from the MongoDB API. Initially, everything was functioning properly. However, upon switching to another route and then returning, the data became undefined. Only after refreshing the browser did it revert back to its ...

The best approach to structuring a type hierarchy in TypeScript for maximum practicality

I am dealing with an abstract base type and multiple subtypes of it, some of which are abstract on their own and have further subtypes. My goal is to define polymorphic functions in TypeScript, where some may be abstract while others have default implemen ...

Expanding Mongoose Schema with Typescript: A Comprehensive Guide

Currently, I am in the process of creating 3 schemas (article, comment, user) and models that share some common fields. For your information, my current setup involves using mongoose and typescript. Mongoose v6.1.4 Node.js v16.13.1 TypeScript v4.4.3 Eac ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

The contents of Ionic views are not stored in a cache, so the controller must

In my ionic application, I have several views. When I launch the app, it takes me to the main view where data is loaded upon initialization of the controller. The issue arises when I navigate away from this view using tabs; sometimes the controller gets d ...

Structure of an Ionic 2 project (visuals)

When working on an Ionic 2 project, where should I store my images? Some sources suggest placing them in www\build\"images_folder", however, the issue arises when you build the project or use the command: ionic serve. This process removes and reb ...

What is the best way to integrate ContextualMenu with Persona in Office Fabric UI React?

Currently, I am utilizing Office Fabric UI React to work on a project. My goal is to implement a ContextualMenu in conjunction with the Persona object. In this particular example, I am demonstrating how ContextualMenu can be applied directly to differ ...

Obtain the inner element located within another element using Protractor

When I first learned about Page Objects and implemented them in my Protractor tests, I encountered a problem with the old code structure. The original code looked like this: var productList = element.all(by.repeater('product in contractsCtrl.contract ...

How can we specify the type based on the argument type of a callback function in Typescript?

How can I specify the parameter type for the callback function handle? const util = (handle: (p) => string) => ({ // I expect the log function's parameter [p] type to come from the handle function's parameter type log: (p: Parameters< ...

Utilizing the Angular @HostListener to retrieve the current viewport width upon loading - a simple guide

Currently, I am utilizing the Angular @HostListener to retrieve the current width of the viewport onResize() in the following manner: @HostListener('window:resize', ['$event']) onResize(event?) { window.innerWidth <= 400 ? ...

Display a loading GIF for every HTTP request made in Angular 4

I am a beginner with Angular and I am looking for a way to display a spinner every time an HTTP request is made. My application consists of multiple components: <component-one></component-one> <component-two></component-two> <c ...

Experiencing a Typescript error when using the useMutation hook from react-query

I am in the process of setting up a subscription form page using next js, react-query, and typescript. However, I am encountering difficulties configuring my API request in typescript. Below is my form component: 'use client'; import React, { Fo ...

Having difficulty retrieving the REST service response in Angular

While I am able to successfully call the REST service within our company's VPN using Firefox and Chrome, I am facing challenges connecting to it from Angular 2. Despite attempting to access the REST service through various methods, I consistently enco ...

The whereabouts of the node_modules folder during the development phase

As I dive into Angular 2 app development, I encountered an issue. Installing node modules in each project folder using npm install seems to be taking up a lot of disk space and causing duplication across multiple projects. This led me to consider creating ...

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...