测试iFrame的位置.href是在jasmine单元测试中设置的

testing that location.href of an iFrame is set in jasmine unit test

本文关键字:单元测试 jasmine 设置 href iFrame 位置 测试 是在      更新时间:2023-09-26

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

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文件。