testing form validation with HTML5 validation API and pseudo-selector with nightwatch API

1.2k Views Asked by At

I have a typical login form with email and password and submit button. Password and email fields are required, i.e. the required attribute on the form is set. This is such that when the user clicks submit and for instance the email field is empty, the error 'Please fill in the field' pops up. That works fine in manual testing.

The issue is that I want to automate that check with nightwatch, and I thought of the following :

  • using :invalid pseudo-selector : .assert.cssClassPresent('.c-textfield__input--password', ':invalid'). However, this fails as it only finds .c-textfield__input--password as a class defined on the input element.

  • access the validity property (.assert.attributeEquals('.c-textfield__input--email', 'validity', 'somevalue)). But that fails too.

Testing if attribute validity of <.c-textfield__input--email> equals "somevalue". Element does not have a validity attribute. - expected "somevalue" but got: "null"

Does anybody know how to automate the form validation testing?

1

There are 1 best solutions below

3
On BEST ANSWER

I was able to do it by using a custom assertion.

In a file test/e2e/custom-assertions/isValidInput.js :

exports.assertion = function (selector, stateAttr, stateValue) {
  this.message = 'Testing if element <' + selector + '> has ValidityState ' + stateAttr + ': ' + stateValue
  this.expected = stateValue

  this.pass = function (val) {
    return val === this.expected
  }

  this.value = function (res) {
    return res.value[stateAttr]
  }

  this.command = function (cb) {
    var self = this
    return this.api.execute(
      function (selector) {
        return document.querySelector(selector).validity
      },
      [selector],
      function (res) {
        cb.call(self, res)
      }
    )
  }
}

Then you can use it that way for example for a required empty input form :

browser
  .assert.isValidInput('#form-input-id', 'valid', false)
  .assert.isValidInput('#form-input-id', 'valueMissing', true)

Don't forget to load the custom assertion. For me, I had to add this in my nightwatch.conf.js file :

module.exports = {
  ...
  custom_assertions_path: ['test/e2e/custom-assertions'],
  ...
}