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.