Dealing with validations in a personalized aid

Recently, I've been exploring CodeceptJs and have found it quite easy to work with. Currently, I'm utilizing it with NightmareJs for testing a gallery that retrieves data from an interface via JSONP to create a list of images enclosed in <div> tags.

As I continue to implement tests, I came across a scenario where I wanted to click on a random element within the gallery, rather than only the first element. This led me to write the following code snippet:

Scenario('clicking on an element adds "selected" class', (I) => {
  I.amOnPage('/')
  I.seeMoreThanElements('#gallery .col-md-3', 1)
  I.clickOnRandomElement('#gallery .col-md-3')
  I.seeElement('#gallery .selected')
})

Alternatively, I thought of grabbing the list of elements so I could choose which one to click on:

Scenario('clicking on an element adds "selected" class', (I) => {
  I.amOnPage('/')
  I.seeMoreThanElements('#gallery .col-md-3', 1)
  const elements = I.grabRandomElement('#gallery .col-md-3')
  const random = getRandomInt(1, elements.length)
  I.click(`#gallery .col-md-3:nth-child(${random})`)
  I.seeElement(`#gallery .col-md-3.selected:nth-child(${random})`)
})

However, the current helpers provided did not entirely meet my needs, prompting me to start implementing a custom helper as outlined in the guide at

Within my configuration, I have included the following:

"helpers": {
  "Nightmare": {
    "url": "http://localhost:3000"
  },
  "DOMElements": {
    "require": "./__tests__/helpers/domelements_helper.js"
  }
}

The domelements_helper.js file currently looks like this:

'use strict'
let assert = require('assert')

class DOMElements extends Helper {
  seeMoreThanElements (locator, count) {
    this.helpers['Nightmare']._locate(locator).then(function (els) {
      return assert(els.length >= count, `Found more than ${count} elements`)
    })
  }
}

module.exports = DOMElements

Unfortunately, the above code does not work as expected, and I find myself a bit confused.

If need be, I am open to transitioning to a more robust assertion library like Protractor or Chai-as-promised. Additionally, the documentation states:

any helper method should return a value in order to be added to promise chain

This statement raises questions about whether I should return a promise or handle everything within the then() block. Furthermore, how should I handle failed assertions?

While exploring the codebase, I came across a Nightmare clientscript, but I'm unsure if it's relevant to my current situation. I'm still in the process of learning how to customize and extend CodeceptJs, so any guidance would be greatly appreciated.

Answer №1

After exploring the codebase extensively, it appears no one has reached this point. Therefore, I'm sharing an answer to shed light on how this function operates.

In summary: here is a quick solution provided below:

/* __tests__/helpers/domelements_helper.js */
const assert = require('assert')

class DOMElements extends Helper {

  seeMoreThanElements (locator, count) {
    return this.helpers['Nightmare']._locate(locator)
      .then((elementsArray) => {
        if (elementsArray.length < count) {
          return assert.fail(elementsArray.length, count, `Found more than ${count} elements`)
        }
      })
  }
}

module.exports = DOMElements

This function operates using promises, necessitating proper failure handling for graceful system failure.

Specifically, _locate() returns a promise, requiring asynchronous handling. This design may seem awkward but is crucial for proper implementation, albeit challenging in the current state.

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

Creating a dual-column checkbox design with CSS only

I'm working with a dynamically generated form element that can only be styled using CSS. I need help achieving a specific layout without making any HTML changes, except for the classes. The "element" and "formField" classes are common and cannot be mo ...

When using window.open in Chrome on a dual screen setup, the browser will bring the new window back to the

When using the API window.open to open a new window with a specified left position in a dual screen setup (screen1 and screen2), Chrome behaves differently than IE and FF. In Chrome, if the invoking screen is on the right monitor, the left position always ...

JavaScript preload with webpack ES6 import for customizable prefetching

Within a large-scale React SPA, my goal is to have certain code chunks loaded only when a user opens or utilizes specific screens or features. Many of our React components are lazily loaded using const Component=React.lazy(() => import('./lazyCode& ...

Is Axios phasing out support for simultaneous requests?

According to the current axios documentation, there is a section that is not very well formatted: Concurrency (Deprecated) It is advised to use Promise.all instead of the functions below. These are helper functions for managing concurrent requests. axio ...

What is the syntax for accessing an element within an array in a function?

This code snippet retrieves an array of users stored in a Firestore database. Each document in the collection corresponds to a user and has a unique ID. const [user] = useAuthState(auth); const [userData, setUserData] = useState([]); const usersColl ...

Upon running the command "React + $ npm start," an error occurred with the code 'ERR_OSSL_EVP_UNSUPPORTED' related to opensslErrorStack

When running $npm start, an error is being thrown: opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ], library: 'digital envelope routines', reason: 'unsupported', code: 'ERR_OSSL_EVP_ ...

Struggling to find a solution to adjust an Angular directive

I am attempting to create a functionality where, upon clicking a button, the user can select one of two images displayed and make the selected image draggable. Currently, my code displays two images with only one being draggable. I am struggling to impleme ...

Updating a .txt file using JavaScript

Is there a method on the client side to add text to a file called text.txt using JavaScript? In Python: f = open("text.txt","w") f.write("Hello World") f.close() The code snippet above would input "Hello World" into the text file. I am looking for a sim ...

A guide on customizing bar colors in a jqPlot stacked bar graph

Is there a way to customize the colors for individual bars in a jqPlot stacked bar chart? I've searched through examples, but they all seem to use the default colors. How can I explicitly set different colors for each bar? Here is the current code sn ...

Converting JSON data to an array using an Ajax request

I am currently working on an HTML project where I have the following code: <div id="main"> <div id="blogcont"> <p></p> </div> <button class="nvgt" id="prev" >Previous</button> <button ...

Encoding and Displaying Characters in HTML with UTF-8

I am experiencing an issue with UTF-8 characters in the page title. I would like to include the music symbol ♫ on the page title. The strange thing is that sometimes it displays correctly (in Google Chrome) and other times it shows a square symbol indic ...

What is preventing me from binding the array index to a model in AngularJS with two-way binding?

I'm currently facing a challenge with a seemingly simple task: I have an array of string values that I want to link to a select element's options, and then connect the index of the chosen value to a variable. However, I have found that neither us ...

Why does the request for server parameter 'occupation=01%02' function correctly, while 'occupation=01%2C02' or 'occupation=01&occupation=02' result in an error?

There seems to be an issue with the parameter when using the API to request data from the server. The value 'occupation=01%02' works correctly when entered directly into the browser URL, but errors occur when using 'occupation=01%2C02' ...

Assigning values to props in a Vue component

I created a Vue component that is supposed to receive the "uploadedFile" prop, but it's not functioning properly. I am only getting the correct information in the $attrs: https://i.sstatic.net/crXmH.png Here is my component: Vue.component('t ...

The jQuery event for clicking is not functioning as expected when trying to display particular data from a JSON array

Three dummy users were created with a JSON array structured like this: var userArray = {"users":[ {"Name":"User1","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2f293f286b1a2935373f2e3233343d74393537">[email& ...

Can scrollHeight ever be less than clientHeight or offsetHeight?

Is it guaranteed that the output of Math.max(el.scrollHeight, el.offsetHeight, el.clientHeight) will always be equal to el.scrollHeight? Typically, clientHeight <= offsetHeight <= scrollHeight. While there are rare instances where clientHeight > ...

Issue encountered when trying to retrieve a database variable from a mapReduce operation in MongoDB

Greetings! I am currently developing an application that utilizes a MongoDB database. Within this database, there exists a user collection where all user data is stored. The structure of a document in this collection is as follows: { "_id" : ObjectId( ...

Utilizing a Dependency Injection container effectively

I am venturing into the world of creating a Node.js backend for the first time after previously working with ASP.NET Core. I am interested in utilizing a DI Container and incorporating controllers into my project. In ASP.NET Core, a new instance of the c ...

Populate object values dynamically through function invocations

Currently, I am involved in a project with a VueJS application that incorporates the following helper class and method: class BiometricMap { static get(bioType) { if (!bioType) { return BiometricMap.default(); } const bioTypes = { ...

Use JavaScript to input array elements into a selection of cells in Excel

At this moment, the loop I am executing successfully retrieves the necessary values. However, I am facing challenges when it comes to inserting these array values into a range of cells. I keep encountering the following error message: Error message: "The ...