Search code examples
javascriptmocha.jsnightmare

How to input text into two elements with the same class using Nightmare.js


I am using Nightmare.js to automatically test logging into a website and I have ran into an issue:

Username:

<input class="form-control" type="text" name="username" placeholder="In-Game Name" autofocus="autofocus" value="">

Password:

<input class="form-control" type="password" name="password" placeholder="Not your In-game password">

As far as I know the only way to focus these is using the class attached to it, but as they are the same it only focus' the username.

Here is my code:

const Nightmare = require("nightmare");
const assert = require("assert");

describe("Login Page", function() {
  this.timeout("30s");

  let nightmare = null;
  beforeEach(() => {
    nightmare = new Nightmare({ show: true });
  });

  describe("given incorrect login", () => {
    it("should fail", done => {
      nightmare
        .goto("https://www.example.com/log-in")
        .on("page", (type, message) => {
          if (type == "alert") done();
        })
        .type(".form-control", "RandomPlayer")
        .type(".form-control", "XFf13lalfla")
        .click(".button")
        .wait(20000)
        .end()
        .then()
        .catch(done);
    });
  });
});

Solution

  • You can use attribute selectors to select only text or password fields.

    • .form-control[name="username"] for username,
    • .form-control[name="password"] for password.

    Example usage:

    enter image description here