Creating a standard login.js file for seamless integration with nightwatch.js testing

When creating tests for my web application, I need to first simulate a login before proceeding with the rest of the tests to access inner pages. Currently, I am in the process of refactoring the code so that I can create an 'include' for common functions like logging in. However, when I move the code snippet below to a separate file and include it using require, it does not function as expected.

For example, the following code successfully logs in and enables other functions when included in the same file above inner screen functions:

// Login screen, creating opportunity

this.LoginScreen = function(browser) {
        browser
                .url(Data.urls.home)
                .waitForElementVisible('#login', 2000, false)
                .click('#login')
                // Remaining login steps...
 
        Errors.checkForErrors(browser);
};     

// Inner functions continue here sequentially

However, once I move the login code to a separate file called Logins.js and include it at the top of the original test file using the correct path:

var Logins      = require("../../lib/Logins.js");

The login simulation no longer works. Any suggestions? Should I consider removing the this.LoginScreen function wrapper and calling it differently when executing it from the external file, or do I need to invoke it again within the original file in addition to the external require statement?

I have also attempted wrapping 'module.exports = {' around the login function in the separate file without success.

Answer №1

Nightwatch offers the ability to execute Page object based tests, allowing you to externalize common test functions for use in your regular tests. This can be accomplished by using the 'page_objects_path' property. I have included a common 'login' function and utilized it in a sample 'single test' within the project found here.

How It Works:

To get started, place your common function in a .js file located within a folder (ex: tests/pages/login.js) and specify the folder path in the Nightwatch config file as shown below:

 nightwatch_config = {
      src_folders : [ 'tests/single' ],
      page_objects_path: ['tests/pages'],

Below is an example of a common login function (login.js):

var loginCommands = {

  login: function() {
    return this.waitForElementVisible('body', 1000)
      .verify.visible('@userName')
      .verify.visible('@password')
      .verify.visible('@submit')
      .setValue('@userName', 'Enter Github user name')
      .setValue('@password', 'Enter Github password')
      .waitForElementVisible('body', 2000)

  }
};

 module.exports = {
      commands: [loginCommands],
        url: function() {
          return 'https://github.com/login';
        },
      elements: {
        userName: {
          selector: '//input[@name=\'login\']',
          locateStrategy: 'xpath'
        },
        password: {
          selector: '//input[@name=\'password\']',
          locateStrategy: 'xpath'
        },
        submit: {
          selector: '//input[@name=\'commit\']',
          locateStrategy: 'xpath'
        }
      }
    };  

Once set up, create an object for the common function in your regular test file and utilize it as follows:

 module.exports = {
      'Github login Functionality' : function (browser) {

    //create an object for login
    var login = browser.page.login();
    //execute the login method from //tests/pages/login.js file
    login.navigate().login();

    //Continue with your tests below:
    // You can also leverage similar Page objects to enhance reusability
        browser
        .pause(3000)
          .end();
      }
    };

Answer №2

The response provided above is indeed accurate, although I encountered some difficulty in figuring out how to input user login details.

After some trial and error, this is the solution I ultimately implemented:

var loginCommands = {

    login: function() {
      return this.waitForElementVisible('body', 1000)
        .setValue("#email", "<some rnd email address>")
        .setValue('#password', "<some rnd password>")
        .click('button[type=submit]')
        .pause(1000)
    }
  };
  
  module.exports = {
    commands: [loginCommands],
      url: function() {
        return 'https://example.com/login';
      }
  };

This code snippet can be utilized in a similar manner as the approved answer, provided here for the benefit of others who might be searching for it.

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

Adjusting column widths in Material-Table: A guide to resizing columns

I am currently using the Material Table library, recommended by Google Material UI as a top data table library. I am facing some issues related to configuring the width of columns in this library. The column's `width` property seems to be functioning ...

Module 'Ember-template-compiler' not found after upgrading to version 2.12.1 - experiencing difficulty locating

Upon updating to Ember cli 2.12.1, I encountered the following error message while attempting to serve ember. Cannot locate module 'C:\Users\assaue\web\client\bower_components\ember\ember-template-compiler' Err ...

The form within the dynamically loaded AJAX content is malfunctioning

My webpage is set up to load content from a separate file (content.php) into a div and refresh it every 5 seconds. In the content.php file, I have a form (basic HTML without javascript) that works fine when accessed directly at (example.com/content.php). ...

The error notification is not appearing in the correct location

I've been troubleshooting my jQuery error function for hours now (including the success function). I'm struggling to figure out how to display an error message only below the button that I click. To help clarify my issue, I've created a JSFi ...

Retrieving information from an ajax array in PHP

I am currently attempting to retrieve an array of data using AJAX on the PHP side, but I am facing difficulties in accessing the values in PHP. Here is my JavaScript code snippet: console.log(obj); $.ajax({ method: 'POST', url: '/in ...

Issue with nextjs not returning the updated object correctly

I'm currently developing a nextjs app that incorporates authentication. There are two key functions that I execute on each page load. The first function checks for the existence of jwt cookies and then calls another function to validate the tokens if ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

Vue.JS and its Onclick event handler allows for dynamic and interactive

These are my two buttons: <button onclick="filterSelection('Action')">Action</button> and <button onclick="filterSelection('Adventure')">Adventure</button> Now, I'm trying to achieve the same fun ...

The image component is missing the necessary "src" attribute even though a valid src value has been provided as a prop

I'm encountering an issue in Next.JS where a component is not recognizing the image source passed through a prop. I am providing the path of an image named "logo.jpg" from the project's public folder. The image successfully displays when used as ...

React - z-index issue persists

My React App with Autocomplete feature is almost complete, but I need some assistance to double-check my code. https://i.stack.imgur.com/dhmck.png In the code snippet below, I have added a search box with the className "autocomplete" style. The issue I a ...

Utilizing Google Maps API to automatically set an address on page load

As a beginner in using the Google Maps API, I have successfully integrated a Google Map into my project. However, I am struggling to figure out how to set specific addresses on the map. I have a list of 2,000 entries in a database, each including an addres ...

React App anchor tag's external links fail to function properly on subsequent clicks when accessed through mobile devices

I have encountered an unusual issue with <a> anchors for external links in my React App on mobile viewports. Initially, clicking an external link opens a new tab just fine on mobile. However, subsequent link clicks on the same or other <a> elem ...

In the event that the get request fails, go ahead and clear the

Currently facing an issue and seeking a solution: I have a game running that retrieves the state of the game periodically. However, if a user logs out, the game ends but continues to send put requests at the set interval. I am exploring options like setti ...

Ensure that the extension is only loaded once Angular has fully loaded

I am currently working on a Chrome extension that incorporates event listeners to elements within a page utilizing Angular 1.2.10. The following code snippet is an example of what I have: window.addEventListener("load", (event) => { var switchButton = ...

What is the best way to extract valid objects from a string in JavaScript?

Currently, my data is being received through a TCP connection. To determine if a string is a valid JSON object, we use the following method: let body = ''; client.on('data', (chunk) => { body += chunk.toString(); try { ...

utilizing BrowserRouter for dynamic routing in react-router-dom

I'm currently facing a challenge with creating a multi-tenant SaaS solution. Each tenant needs to be able to use a subdomain, so that I can extract the subdomain from the URL and make a call to a REST API to retrieve data specific to that tenant. For ...

Is the value of the object in the array already present in another array of objects?

Plunker - http://plnkr.co/edit/jXdwOQR2YLnIWv8j02Yp In my angular project, I am working on a view that displays a list of users in the main container (array-A) and a sidebar with selected users (array-B). The first array (A) contains all users: [{ $$has ...

Do we need to include href in the anchor tag?

Why am I unable to display the icon within the <anchor> element without using the href attribute? The icon only appears when I set the href attribute to "". Even if I manage to show the icon by adding href="", adjusting the size with width and height ...

Error encountered: java.net.SocketException - Connection reset when executing driver.close() or driver.quit() in Selenium

Whenever I try using the driver.close() or driver.quit() statement, I consistently encounter a java.net.SocketException: Connection reset. Despite this exception, my tests continue to run smoothly without any interruption. However, I am curious to understa ...

Utilizing Robot Framework to select CSS attributes

The Selenium documentation provides an example of how to use Get Element Attribute: ${id}= Get Element Attribute css:h1 id However, I encountered a problem with this selector: ${VISIBILITY}= Get Element Attribute css:visibility mySidebar I ...