【问题标题】:method is not defined when trying to use it as a static method尝试将其用作静态方法时未定义方法
【发布时间】:2017-07-18 10:44:21
【问题描述】:

我正在尝试使用静态方法以便在外部使用它。

实用程序文件:

'use strict'
function utils(){}
utils.staticMethod1 = function(){
alert("foo");
};
module.exports =  utils();
主文件:

'use strict;'
     let HomePage = require('../page/home_page.js');
let utilsPage = require('../utils/utils.js');
    describe("login to website",function(){
         let employeeId;
         let employeeBday;
         let home = new HomePage();
         
      beforeEach(function(){
           
            browser.driver.get("http://foo.com/");     
        });
       
            it("should succees picking a present",function(){
                utilsPage.staticMethod1();
        });
    });

但我不断收到错误消息:Failed: utils is not defined

【问题讨论】:

  • this 在(假定的)静态方法中没有意义!另外,如果您打算使用 stacksn-ps 来演示问题 - 确保它们正常工作(即,做某事并且不要出错)
  • 如何导入utils文件?
  • @YuryTarabanko - 就此而言,我什至看不到 utils 是如何导出
  • 我没有导入 utils 文件。我想使用 utils.staticMethod1();会做的工作。
  • @Jamiec 这就是我问的原因:)

标签: javascript protractor


【解决方案1】:

您的页面文件:

'use strict';

var Utils = function(){
   this.methodTest = function(){
      console.log("Something"); //alert(this);
   };
};

module.exports = Utils;

您的规格文件:

'use strict;'

let Utils = require('../page/utils.Page.js');

describe("login to website",function(){
     let employeeId;
     let employeeBday;
     let utils = new Utils();

     beforeEach(function(){ 
         browser.driver.get("http://foo.com/");     
     });

     it("should success picking a present",function(){
         utils.methodTest();
         expect(browser.getTitle()).toEqual('SomethingToGetAnError');
     });

});

你应该稍微了解一下在量角器中使用静态方法,它们会让你陷入困境。

Explanation

Better explanation about Page Objects Pattern in testing

【讨论】:

  • 一般来说,我确实使用页面对象模式,但出于其他原因需要使用外部文件。
  • 如果您需要使用外部文件,例如用于表单的信息,您应该像将 json 文件加载到测试中一样加载它。例:browser.params.users = require('./shared.params.' + countryCode + '.json').users;
  • 我使用了您的代码,但出现错误。错误:TypeError:无法设置未定义的属性“方法”
  • @YanivEliav 更改页面函数以返回量角器可以处理的实际内容。比如一个console.log,并在Spec文件中实现一些期望Edited post with this elements
猜你喜欢
  • 2016-04-23
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
相关资源
最近更新 更多