2017-04-06 65 views
0

我在一个JS文件编写的函数TakeScreenshot说base.js文件,该文件保存截图和下面返回我的截图路径的实现。收到错误mesasge“this.TakeScreenshot不是一个函数”在量角器

this.TakeScreenshot = function(screenShotName) { 
//some stuff..... 
     browser.takeScreenshot().then(function (png) { 
      var stream = fs.createWriteStream(screenshotPath); 
      stream.write(new Buffer(png, 'base64')); 
      stream.end(); 
    }); 
     return screenshotPath; 
    }; 

I am calling the above function in another function called "isTruelyPresent". This function will take a screenshot if element is present/not present on UI. The implementation is as below: 

this.isTrulyPresent = function(elementToCheckVisibilityOf, element2) { 
      return elementToCheckVisibilityOf.isDisplayed().then(function (isDisplayedd) { 
      var myObj; 
      myObj = this.TakeScreenshot(element2); 
      // some stuff 
      console.log('isDisplayed'+isDisplayedd); 
      return isDisplayedd; 
    }).then(null, function (error) { 
      var myObj; 
      myObj = this.TakeScreenshot("ErrorSS"); 
      console.log('A NoSuchElement exception was throw because the element is NOT displayed so we return false'); 
      return false; 
     }); 
    }; 


Protractor script is throwing an error "this.TakeScreenshot is not a function". Could any one please help me to resolve the issue. 
+0

注意:isTrulyPresent函数存在于异步编程的相同JS文件(base.js) –

+0

中,因此不能在回调方法内使用'this'关键字。相反,在函数作用域内声明一个新变量并将'this'赋值给新创建的变量。在你的情况下,Inside'isTrulyPresent'方法创建一个变量,如'var self = this;',并使用'self.TakeScreenshot()'来调用该方法。 –

+0

谢谢@SudharsanSelvaraj ..非常感谢您的帮助。如果我有任何问题,我会尝试您的解决方案并回复您。非常感谢朋友。 –

回答

0

的首先是意识到存在isPresent之间的差(检查如果一个元素存在于DOM)和isDisplayed(检查如果一个元素存在于DOM和可见)。如果DOM中不存在元素,则方法isDisplayed()将会失败。你现在正在捕捉这个错误,这也是你想要的吗?

其次每个function可以有它自己的this范围。这意味着您的this.TakeScreenshot("ErrorSS")可以参考this-function(error){}的范围,而不是您要参考的this

This ;-) doc可能有助于解决这个问题。我通常使用的是arrow功能,请参阅链接。

+0

非常感谢朋友。该文件有更多信息。绝对会帮助我。 –

+0

它解决了你的问题吗? – wswebcreation

+0

没有@wswebcreation。我没有运气:( –

相关问题