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

Activate the popup for sharing or bookmarking by clicking on a regular link

I am currently utilizing a Share/Bookmark script: <div class="singles-right"> <a href="#" class="bookmark"></a> <script type="text/javascript" src="http://static.addinto.com/ai/ai2_bkmk.js"></script> <a href="#" clas ...

Tips for dividing a hefty sub file into individual chunks using webpack 2

I'm currently facing a challenge with importing a sizable file into my react project that has been Chunked and Uglified by webpack 2. Our codebase is separated into chunks, with one of them weighing in at 29MG. I am looking to exclude this large file ...

Is it possible to view a PDF file stored on a mobile device using Appium for Android?

Looking to validate the text found in a PDF file. The first step is to extract the data from the PDF file. Is there a method to accomplish this task if the file is stored on a mobile device? Note: File access is limited to mobile devices. ...

What is causing this to function properly on Firefox but not on Chrome or IE?

After clicking the process_2banner button on my html page, a piece of code is executed. Surprisingly, this code performs as expected in Firefox, but not in Chrome or Internet Explorer. In those browsers, although the ajax code is triggered, the div spinner ...

Selenium is encountering an issue where it is unable to automatically download files, as the download confirmation

While reviewing someone else's code, I encountered an issue with automatically downloading PDF files from a web page using selenium. Despite setting the browser.helperApps.neverAsk.saveToDisk property to the PDF mime type, I am still getting the fire ...

Updating the display text length on vue-moment

Currently, I am attempting to showcase an array of numbers const days = [1, 7, 14, 30, 60] in a more human-readable format using vue-moment Everything is functioning correctly {{ days | duration('humanize') }} // 'a day' // '7 d ...

Guide on how to modify a static css file using Node.js

Issue Whenever a user updates the theme on the front-end, my Node.js API needs to update the static CSS file located in a public folder set up by Express. This way, when pages are served again with <link href="public/theme.[userId].[hash].css", the use ...

Struggling to reveal concealed items on a webpage using jQuery and attempting to cycle through an array without success

Looking to display or hide certain sections on a page based on specific conditions. I want to only show the sections of the page that contain words from the conditionsToShow array. function hideWorkflowConditions() { // initially hide the elements ...

The property of undefined map cannot be read

import React from 'react'; import { Card, Text } from "react-native-paper"; import { SafeAreaView, } from "react-native"; class HackerNewsClone extends React.Component { constructor(props) { super(props); this.sta ...

The issue with ng-change is causing the previously selected drop down option to be cleared

After successfully implementing live searching with ng-change, I encountered an issue with a pre-selected drop-down box. Despite setting the selected="selected" attribute to make option three the default selection, the drop-down box jumps to the top optio ...

Various concatenated and compressed JavaScript files across multiple HTML documents within a single application

In my express.js application, I have different routes such as /home and /dashboard. For example, on the home page, I include: jquery.js, underscore.js, somemodule1.js, somemodule2.js. On the dashboard, I include: jquery.js, underscore.js, somemodule3.js, ...

Implementing onbeforeunload event on body tag with jQuery for Chrome and IE browsers

My current system includes a feature where I need to confirm with the user if they really want to leave the page once a dirty flag is set. I have implemented the following code - when viewing in Firefox, I can see that the page source shows the onbeforeun ...

Adding a new element with Jquery when a dropdown option is selected

What is causing this issue to not function properly? <script> $(document).ready(function(){ $('#custom_field option').click(function(){ $('#custom_field_input').append('<tr><td></td> ...

Troubleshooting Bootstrap bug caused by rollupPluginBabelHelpers

I am currently working on a Bootstrap 4 website. I noticed that in Internet Explorer, the modal works fine when opened for the first time, but then displays an error in the console and does not open when trying to do so a second time on the same window. On ...

HashRouter prevents the Framer Motion exit animation from functioning properly

Unfortunately, the exact same question was posted here. Despite no answers provided, I will share my problem as well: Originally, I was using BrowserRouter for routing, but faced issues with refreshing, so I switched to a simple solution using HashRouter ...

Is file timestamp utilized by Apache to verify if a resource has been changed?

Currently, I am working on an HTML page that references a large JavaScript file (1MB+) that is rarely updated. According to this source, the JavaScript file will not be resent if it hasn't been modified. I'm curious about how Apache determines i ...

jQuery-chosen - Transfer custom attribute from chosen option to list when selected

I have a selection list as shown below: <select data-placeholder="Choose users" style="width:350px;" multiple class="chosen-select" tabindex="8"> <option data-user-id="1">User1</option> <option data-user-id="3">User2</op ...

Changing directions while the script is running

For my web site testing, I created a script using Tampermonkey that randomly browses the site and modifies parameters. Sometimes I need to navigate to a different page by either using window.location.replace(URL) or by clicking a button with the script l ...

Click to switch CodeMirror's theme

http://jsbin.com/EzaKuXE/1/edit I've been attempting to switch the theme from default to cobalt and vice versa, toggling each time the button is clicked. However, I am facing an issue where it only switches to the new theme once and doesn't togg ...

Customize RequireJS dependencies for flexible dependency injection

Currently, I am faced with integrating a component that would greatly benefit from Dependency Injection (DI) into an existing framework where DI was not considered during its initial design. The configuration defining dependencies is sourced from a backend ...