通过require通用函数文件添加全局变量

时间:2019-01-22 19:07:39

标签: javascript protractor

我正在切换到量角器和Jasmine以执行我们的自动化脚本时进行POC。我正在尝试建立一个初步的框架,但在尝试将我的概念转化为现实时遇到问题。

我已经设置了三个文件:conf.js,spec.js和cf.js。 Conf.js是特定于testplan的配置文件,spec.js包含实际测试,而cf.js包含我将在所有测试计划中使用的常用功能。我试图在cf.js中包含一个变量,以包含在browser.get调用中使用的起始URL。到目前为止,我还无法使它正常工作。我试过在// commonfunctions //函数声明之前以及在函数本身内部,在cf.js中声明它。正确的方法是什么?

cf.js

    var commonfunctions = function () {
      global.StartPage = 'http://google.com/';
      this.ccClick = function (clickElement) {
        browser.wait(protractor.ExpectedConditions.visibilityOf(clickElement),
         this.defaultWait);



  browser.wait(protractor.ExpectedConditions.elementToBeClickable(clickElement),
     this.defaultWait);
        clickElement.click();
    };
    // Common text search
      this.ConfirmText = function(testElement, compareString) {
        browser.wait(protractor.ExpectedConditions.visibilityOf(testElement), 
10000);
        expect(testElement.getText()).toEqual(compareString);
      };
    };
    module.exports = new commonfunctions();

spec.js

  beforeEach(function() {
    browser.waitForAngularEnabled(false);
    browser.get(commonfunctions.StartPage);
  });

目前,它无法导航到该网页。

3 个答案:

答案 0 :(得分:0)

这应该可行,我之前也发布了类似的答案,但是如果您对这种方法还有其他疑问,请告诉我。我采用的方法是要求onPrepare中的通用功能文件作为全局变量。这样,从文件导出的所有内容都可以在所有测试中访问。

Storing global variable in a separate file for Protractor Tests

答案 1 :(得分:0)

您在以下代码中犯了一个错误:

// cf.js
var commonfunctions = function () {
      global.StartPage = 'http://google.com/';

// spec.js
beforeEach(function() {
  browser.waitForAngularEnabled(false);
  browser.get(commonfunctions.StartPage);
});

// you define `StartPage` to a global variable, not a property of `commonfunctions`, 
thus you shouldn't refer it from `commonfunctions`, but from `global` as following:

browser.get(global.StartPage)

或者您将StartPage定义为commonfunctions的属性

// cf.js
var commonfunctions = function () {
   this.StartPage = 'http://google.com/';
   // use `this` at here, rather than `global`

// spec.js
beforeEach(function() {
  browser.waitForAngularEnabled(false);
  browser.get(commonfunctions.StartPage);
});

答案 2 :(得分:0)

将以下内容添加到您的config.js

baseUrl: 'http://google.com/',

要按如下所示在测试中使用

browser.get(browser.baseUrl);

希望这对您有帮助

相关问题