2012-08-31 160 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

相关问题