javascriptasynchronousasync-awaitnightwatch.jsobject-property

Assigning to object doesn't work


I'm using Nightwatch.js and recently I spotted an interesting behaviour of the code.

I was trying to replace callback structures with async/await commands from JS6.

Initially

Initially I started with this code. It checks if we have 2 tabs in the browser window.

# main.js

client.windowHandles((result) => {
    client.verify.equal(result.value.length, 2);
});

Working code

And I replaced it with:

# main.js

const { assignVariable } = require("../../utils/callbacks");

let windows = {};

await client.windowHandles(assignVariable(windows));
client.verify.equal(windows.value.length, 2);

Where assignVariable is:

# callbacks.js

const assignVariable = (variable) => {
    return (result) => {
        variable.value = result.value;
    };
};

module.exports = { assignVariable };

And this code works.

Not working code

Strange things are happening when I want to change assignVariable to:

# callbacks.js

const assignVariable = (variable) => {
    return (result) => {
        variable = result;
    };
};

module.exports = { assignVariable };

Problem

Then assingVariable seems to doesn't have an impact at all. I was debugging this lines and the assignment in assignVariable is executed but the object windows still equals {} when we are back in main.js.

I hope I've explained it clearly.

P.S. This is my 1st question in StackOverflow, so be patient with me. :)


Solution

  • The first one works because you're mutating an object that you have a shared reference to. The second one (variable = result) merely assigns a value to a local variable. There's no connection to the windows variable in the caller's scope. Remember: when passing a variable to a function, you're passing only the value, not a reference to that variable.