Previously-defined variable not working in other parts of test in nightwatchjs

83 Views Asked by At

I'm using nightwatchjs and the ssh2 npm package to test that a file name is present in a location, and asserting that it's correct.

My code is as follows;

var Client = require('ssh2');
var conn = new Client();
var longFileNamePrdArray;


module.exports = {
    before:
    conn.on('ready', function(browser) {
        console.log('Client :: ready');
        conn.sftp(function(err, sftp) {
            if (err) throw err;
            sftp.readdir('parkersreviewcontent/', function (err, list) {
                if (err) throw err;
                list.map(a => a.longname);
                longFileNamePrdArray = list[1].longname;
                conn.end();
            });
        });
    })
    .connect({
        host: '*hostname*',
        port: 22,
        user: '*user*',
        password: '*password*',
    }),
    'Test Zen Reviews production file is listed': function (browser) {
        console.log(longFileNameStgArray);
   },
    'Closing the browser': function (browser)  {
        browser.browserEnd();
    },
};

However, this results in undefined being outputted for longFileNamePrdArray.

If I move the console.log command inside the before code block, then the filename is correctly displayed as follows;

-rwxr--r-- 1 - - 2492238 Feb 28 06:37 parkers-reviews-staging.xml

but when I move it outside the before block and into my test block, it fails with the undefined output.

I thought by defining longFileNamePrdArray and stating it at the beginning of the test script it work 'carry across' the longFileNamePrdArray value into the test block, but it's not.

Any help and assistance would be really appreciated. Thanks.

1

There are 1 best solutions below

0
On

I fixed this by using the done callback.

So my working code looks like this;

var Client = require('ssh2');
var conn = new Client();
var longFileNamePrdArray;

module.exports = {
    before: function(browser, done) {
    conn.on('ready', function(browser) {
        console.log('Client :: ready');
        conn.sftp(function(err, sftp) {
            if (err) throw err;
            sftp.readdir('parkersreviewcontent/', function (err, list) {
                if (err) throw err;
                list.map(a => a.longname);
                longFileNamePrdArray = list[1].longname;
                conn.end();
                done();
            });
        });
    })
    .connect({
        host: '*hostname*',
        port: 22,
        user: '*user*',
        password: '*password*',
    }),
    'Test Zen Reviews production file is listed': function (browser) {
        console.log(longFileNameStgArray);
   },
    'Closing the browser': function (browser)  {
        browser.browserEnd();
    },
};