hackp0int
hackp0int

Reputation: 4161

Nightwatch.js setValue and execute

Nightwatch 0.9.19
Node: 9.3.0
OS: darwin x64

exports.command = function (username, password) {
    const TIMEOUT = 6000;
    const USER_NAME = '[name="username"]';
    const PASSWORD = '[name="password"]';
    const BODY = 'body';
    const FORM = 'form';
    if (!username) {
        username = this.globals.username;
    }
    if (!password) {
        password = this.globals.password;
    }
    console.log('login', this.globals.baseUrl, username, password);

    this.url(this.globals.baseUrl)
        .waitForElementVisible(BODY, TIMEOUT)
        .setValue(USER_NAME, username)
        .getValue(USER_NAME, (result) => {
            console.log(`=====> Username is: ${result.value} <=====`);
        })
        .waitForElementVisible(USER_NAME, TIMEOUT)
        .waitForElementVisible(PASSWORD, TIMEOUT);

    this
        .execute(function (data) {
            document.querySelector(PASSWORD).value = password;
            return true;
        }, [], null)
        .pause(TIMEOUT)
        .getValue(PASSWORD, (result) => {
            console.log(`=====> Password is: ${result.value} <=====`);
        })
        .submitForm(FORM)
};
  1. When I set hard coded password: 1q2w3e4r it's works. If I use variable it doesn't.
  2. .setValue(password) ==> result: 1q2we4r (missing: 3)

Upvotes: 0

Views: 1407

Answers (1)

akrn
akrn

Reputation: 758

I see that you're trying to set a value on the password field using the code below:

this
    .execute(function (data) {
        document.querySelector(PASSWORD).value = password;
        return true;
    }, [], null)

Both PASSWORD and password variables within the function are undefined at the time of execution.

The issue here is that basically the function you pass to execute will be run in the context of the webpage you're testing (browser JavaScript engine) and not in the context of current script (node.js).

However, for the case when you need to pass some arguments to such function, you can use the 2nd parameter of execute() which is basically an array of arguments passed to your function.

After fixing the code snippet above you should get the following:

this
    .execute(function (PASSWORD, password) {
        document.querySelector(PASSWORD).value = password;
        return true;
    }, [PASSWORD, password], null)

Documentation on execute(): http://nightwatchjs.org/api/execute.html

Upvotes: 5

Related Questions