Reuse the browser session for Selenium WebDriver for Nightwatch.js tests

本小妞迷上赌 提交于 2019-11-29 14:13:58

Using this function to chain together files:

extend = function(target) {
    var sources = [].slice.call(arguments, 1);
    sources.forEach(function (source) {
        for (var prop in source) {
            target[prop] = source[prop];
        }
    });
    return target;
}

and adding files to this master file like this:

require("./testName.js");
module.exports = extend(module.exports,testName);

and having the test file look like this:

testName = {
    "Test" : function(browser) {

        browser
            // Your test code
    }
};

allowed me to have one file that could link all the tests to, and keep the same browser session the entire time. It runs the tests in the order you require them in the master file and if you do not call browser.end() until the last test is finished it will use one browser window for all tests.

Reuse of session is not good idea as you may run tests in different oreder, but You could place login code into before function or even extract it into custom commands.

Example: https://github.com/dimetron/backbone_app/blob/master/nightwatch/custom-commands/login.js

1 - In nightwatch config add

"custom_commands_path" : "nightwatch/custom-commands",

2 - Create custom-commands/login.js

exports.command = function(username, password, callback) {
    var self = this;
    this
        .frame(null)
        .waitForElementPresent('input[name=username]', 10000)
        .setValue('input[name=username]', username)
        .waitForElementPresent('input[name=password]', 10000)
        .setValue('input[name=password]', password)
        .click('#submit');

    if( typeof callback === "function"){
        callback.call(self);
    }
    return this; // allows the command to be chained.
};

3 - Test code - Before using .login(user, apssword)

 module.exports = {

  before: function(browser) {
    console.log("Setting up...");
    browser
      .windowSize('current', 1024, 768)
      .url("app:8000/") 
      .waitForElementVisible("body", 1000)
      .login('user', 'password')
  },

  after : function(browser) {
    browser.end()
    console.log("Closing down...");
  },

  beforeEach: function(browser) {
    browser
      .pause(2000)
      .useCss()
  },

  "Test 1": function(browser) {
    browser
      .assert.containsText("#div1", "some tex")
      .pause(5000);
  },

  "Test 2": function(browser) {
    browser
      .assert.containsText("#div2", "some text")
      .pause(5000);
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!