测试iFrame的位置.href是在jasmine单元测试中设置的
testing that location.href of an iFrame is set in jasmine unit test
有人知道为什么下面的单元测试没有通过吗?
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位置不起作用有什么原因吗?
(我使用Chutzpah v1.4.2运行测试,使用Visual Studio加载项和命令行。)
此测试失败的原因有很多:
- 尝试在
<iframe>
标记中加载"about:history"至少在Firefox和Chrome中都会导致异常(在Chutzpah下的PhantomJS中可能会这样做) - 尝试加载除运行jasmine的域之外的其他域将不起作用,因为您无法再访问href属性。这是由于浏览器的跨域安全限制;Firefox显示"
Error: Permission denied to access property 'href'
",Chrome显示"Unsafe JavaScript attempt to access frame with URL
"。框架会显示出适当的坚韧 - 即使您加载的URL与testRunner在同一个域中,href也不会立即反映该更改,第二个预期将失败(href仍等于'about:blank'),直到加载iframe,这是在您的测试已经执行之后
以下修改后的代码使用Jasmine waitsFor()
和runs()
来解释最后一个问题。它将等待1000ms以满足条件,从而使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:');
});
});
});
请注意,我还使用了"about:"(不带"blank"),这是我所知道的唯一一个不会引发异常的其他URL。然而,最好使用其他东西,可能是同一域中的一对静态fixture文件。
相关文章:
- Jasmine单元测试在监视服务方法时失败
- 测试iFrame的位置.href是在jasmine单元测试中设置的
- 在Karma Jasmine单元测试用例中检查日期格式
- AngularJS:指令限制:“E”阻止在Jasmine单元测试中调用元素click()事件
- 使用Jasmine进行角度单元测试:如何删除或修改spyOn
- 将Jasmine JavaScript单元测试与TFS Build CI集成的简单方法
- 使用Jasmine框架对javascript进行单元测试
- 当使用 Jasmine 对我的 angularJS 应用程序进行单元测试时,$interval是未定义的
- 为什么这个 Angular 指令没有在 Jasmine 单元测试中编译
- 如何使用 Jasmine 对链式方法进行单元测试
- 单元测试:AngularJS + Karma + Jasmine,加载本地JSON
- Jasmine抱怨在单元测试中导入的css
- 单元测试 Karma Jasmine 语法错误:在“&”角度指令绑定上解析错误
- Jasmine + Node.js用于服务器端单元测试.如何运行测试
- 单元测试窗口.onerror with jasmine.
- 在 Karma/Jasmine 单元测试中注入 Angular $timeout服务的真实实现
- 使用 Jasmine 进行单元测试,expect().toBeVisible()
- expect - response在AngularJS单元测试(Jasmine)中不起作用
- 重构单元测试(Jasmine)
- 单元测试——jasmine, javascript