2012-08-31 207 views
1

任何人都知道爲什麼下面的單元測試不通過?測試iFrame的location.href是否在jasmine單元測試中設置

describe("just a test", function() { 
    it("should set the iframe location", function() { 

     $('body').append('<iframe id="myiframe" name="myiframe"</iframe>'); 

     expect(window['myiframe'].location.href).toEqual('about:blank'); 

     window['myiframe'].location.assign('about:history'); 
     expect(window['myiframe'].location.href).toEqual('about:history'); 
    }); 
}); 

這僅僅是簡化代碼,試圖找出爲什麼一個真正的考驗不工作 - 我不打擾關於清理或任何東西。

第二次預期失敗。有沒有理由改變這樣的iframe位置不應該工作?

(我正在與放肆5.0上測試,都與Visual Studio中添加和命令行。)

回答

1

有很多原因造成的測試失敗:

  • 嘗試在標記中加載「about:history」至少會在Firefox和Chrome中引發異常(並且可能會在PhantomJS的Chutzpah下執行此操作)。
  • 試圖加載除了運行茉莉花以外的其他域將不起作用,因爲您無法再訪問href屬性。這是由於瀏覽器的跨域安全限制; Firefox說'Error: Permission denied to access property 'href'',Chrome說'Unsafe JavaScript attempt to access frame with URL'。該框架將顯示適當的強硬。
  • 即使加載與testRunner位於同一個域中的URL,href也不會立即反映該更改,但第二個expect將會失敗(href仍然等於'about:blank'),直到iframe加載完畢,在你的測試已經執行之後,這種方式是很重要

以下修改後的代碼使用Jasmine waitsFor()runs()來解釋最後一個問題。它將等待1000毫秒才能滿足條件,允許iframe完成加載。我將原始規範留在了wait()塊中,但是如果發生超時,waitsFor也會失敗。

describe("just a test", function() { 
    it("should set the iframe location", function() { 
    $('body').append('<iframe id="myiframe" name="myiframe"</iframe>'); 
    expect(window['myiframe'].location.href).toEqual('about:blank'); 

    window['myiframe'].location.assign('about:'); 

    waitsFor(function(){ 
     return window['myiframe'].location.href == 'about:' 
    },1000); 
    runs(function(){ 
     expect(window['myiframe'].location.href).toEqual('about:'); 
    }); 
    }); 
}); 

請注意,我用的也是「一下:」(withouth的的「空白」),因爲是唯一的-other- URL我知道,不會拋出異常。但是,使用其他的東西,也許是同一個域中的一對靜態夾具文件是個好主意。

+0

謝謝 - 我沒有意識到最後一個問題,即在負載完成之前,href屬性並不反映更改。 – GarethOwen

相關問題