【问题标题】:testing that location.href of an iFrame is set in jasmine unit test测试 iFrame 的 location.href 是否在 jasmine 单元测试中设置
【发布时间】:2012-08-31 11:45:17
【问题描述】:

有人知道为什么下面的单元测试没有通过吗?

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 插件和命令行。)

【问题讨论】:

    标签: javascript iframe browser jasmine chutzpah


    【解决方案1】:

    这个测试失败的原因有很多:

    • 尝试在 &lt;iframe&gt; 标签中加载“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() 来解决最后一个问题。它将等待 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:');
        });
      });
    });
    

    请注意,我还使用了“about:”(没有“空白”),这是我知道的唯一一个不会引发异常的 -other- URL。但是,使用其他东西是个好主意,也许是同一域中的一对静态夹具文件。

    【讨论】:

    • 谢谢 - 我不知道最后一个问题,即 href 属性在加载完成之前不会反映更改。
    猜你喜欢
    • 2023-01-13
    • 2018-04-16
    • 2017-04-14
    • 2017-04-04
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多