将测试模块导入主测试 - 守夜人

时间:2018-01-31 13:40:50

标签: selenium nightwatch.js

我正在学习Nightwatch并成功完成了我的第一次测试。我现在想要更好地组织我的测试,并使用一堆可重用的常用测试,我可以继续进行主要测试。我尝试使用下面的代码进行设置,但我对Node导出并不太熟悉(事实上,我更喜欢使用es6导入/导出,所以如果有人能说明这一点我和#39;感激不尽)所以我可能犯了一些根本性的错误:

文件结构

Tests
 -auth
  -- auth.js
 index.js

nightwatch.json

{
  "src_folders" : ["tests"],
  "output_folder" : "reports",
  "selenium" : {
    "start_process" : true,
    "server_path" : "./bin/selenium-server-standalone-3.8.1.jar",
    "log_path" : "",
    "port" : 4444,
    "cli_args" : {
      "webdriver.chrome.driver" : "./bin/chromedriver"
    }
  },
  "test_settings" : {
    "default" : {
      "launch_url" : "http://localhost",
      "selenium_port"  : 4444,
      "selenium_host"  : "localhost",
      "desiredCapabilities": {
        "browserName": "chrome",
        "javascriptEnabled": true,
        "acceptSslCerts": true
      }
    }
  }
}

的package.json

{
  "name": "mostesting",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test-e2e": "nightwatch"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "babel-plugin-add-module-exports": "^0.2.1",
    "nightwatch": "^0.9.19",
    "selenium-webdriver": "^4.0.0-alpha.1"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-preset-es2015": "^6.24.1"
  }
}

index.js

const auth = require('./auth/auth.js')

module.exports = {
  'Log into system': auth.login()
}

auth.js

exports.login = function (client) {
  client
    .url('http://myurl.co.uk')
    .waitForElementVisible('body', 1000)
    .assert.title('Reach - Log in')
    .assert.visible('#UserName')
    .setValue('#UserName', 'XXXX')
    .assert.visible('#Password')
    .setValue('#Password', 'XXXX')
    .assert.visible('input[value="Login"]')
    .click('input[value="Login"]')
    .waitForElementVisible('img.test', 10000, false)
}

当我运行测试时,它会打开,它会运行并通过,但最后我得到以下控制台错误:

OK. 6 assertions passed. (8.549s)

There was an error while starting the test runner:

TypeError: Cannot read property 'url' of undefined
    at Object.exports.login (/Applications/MAMP/htdocs/mostesting/tests/auth/auth.js:3:5)
    at Object.<anonymous> (/Applications/MAMP/htdocs/mostesting/tests/index.js:4:27)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at new Module (/Applications/MAMP/htdocs/mostesting/node_modules/nightwatch/lib/runner/module.js:7:23)

请有人能指出我出错的地方吗?

非常感谢提前。

1 个答案:

答案 0 :(得分:1)

当您定义测试运行时,无需调用测试运行函数auth.login()。你需要的是导出这个功能,所以Nightwatch可以执行它:

// index.js

const auth = require('./auth/auth.js')

module.exports = {
    'Log into system': auth.login
}