2017-02-09 99 views
0

對於protracor有點新手,但我試圖實現的基本上是一個檢查(從另一個函數)執行一個操作,然後執行相同的檢查(從早先的相同函數)。兩個函數的比較結果

我曾嘗試以下,但unforunately得到Failed: first is not defined

checkCanvasWidth: { 
    value: function() { 
     return element(by.css("div[class='canvasWrapper'] > canvas")).getAttribute("width").then(function(width) { 
      return width; 
     }); 
    } 
}, 


zoomIn: { 
    value: function() { 
     this.checkCanvasWidth().then(function (width) { 
      var first = width; 
      console.log("before:" + width); 
     }); 

     //performs a click 
     this.clickZoomIn(); 

     this.checkCanvasWidth().then(function (width) { 
      var second = width; 
      console.log("after:" + width); 
     }); 

     expect(first).toBeGreaterThan(second); 
    } 
} 

任何幫助將大規模感激!

回答

0

定義this.checkCanvasWidth()的第一個和第二個外部。函數創建範圍,因此只有您使用checkCanvasWidth的函數才能分別訪問第一個和第二個。您必須在這些函數上方的範圍中定義它們,以便期望函數也可以看到這些變量。

zoomIn: { 
    value: function() { 
     var first, 
      second; 
     this.checkCanvasWidth().then(function (width) { 
      first = width; 
      console.log("before:" + width); 
     }); 

     //performs a click 
     this.clickZoomIn(); 

     this.checkCanvasWidth().then(function (width) { 
      second = width; 
      console.log("after:" + width); 
     }); 

     expect(first).toBeGreaterThan(second); 
    } 
} 

PS:如果checkCanvasWidth()返回一個承諾,你就必須重寫這個整體功能,因爲要在其後的第一和第二ahve被設置爲做expect()電話。

無極版:

zoomIn: { 
    value: function() { 
     var first, 
      second; 
     this.checkCanvasWidth().then(function (width) { 
      first = width; 
      console.log("before:" + width); 
      if (first && second) { 
       expect(first).toBeGreaterThan(second); 
      } 
     }); 

     //performs a click 
     this.clickZoomIn(); 

     this.checkCanvasWidth().then(function (width) { 
      second = width; 
      if (first && second) { 
       expect(first).toBeGreaterThan(second); 
      } 
     }); 
    } 
} 
+0

謝謝Shilly,我確實需要承諾版本!這是我正在努力,但沒有意識到 –

0

你需要把這些變量firstsecond可用的功能。 Javascript has function scope,所以你定義的方式firstsecond它們不能在函數外部訪問。

因此,當你編寫下面的代碼時,變量second只能被匿名函數訪問。

this.checkCanvasWidth().then(function (width) { 
      var second = width; 
      console.log("after:" + width); 
     }); 

所以,你可以聲明變量firstsecond之外,使他們可以訪問,然後設置,然後處理程序內的值來設置值。

zoomIn: { 
    value: function() { 
     var first ; 
     var second ; 
     this.checkCanvasWidth().then(function (width) { 
      first = width 
      console.log("before:" + width); 
     }); 

     //performs a click 
     this.clickZoomIn(); 

     this.checkCanvasWidth().then(function (width) { 
      second = width 
      console.log("after:" + width); 
     }); 

     expect(first).toBeGreaterThan(second); 
    } 
}