Вопрос

Anyone know why the following unit test does not pass?

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');
    });
});

This is just simplified code to try and find out why a real test does not work - I'm not bothered about cleaning up or anything.

The second expect fails. Is there a reason why changing the iframe location like this should not work?

(I am running the test with Chutzpah v1.4.2, both with the Visual Studio add in and from the command line.)

Это было полезно?

Решение

There are many reasons for this test to fail:

  • Trying to load 'about:history' in an <iframe> tag will cause an exception at least in both Firefox and Chrome (and will probably do so in PhantomJS's under Chutzpah).
  • Trying to load a different domain other than where jasmine is running will not work because you can't access the href property anymore. This is due to the browser's cross-domain security restrictions; Firefox says 'Error: Permission denied to access property 'href'', and Chrome says 'Unsafe JavaScript attempt to access frame with URL'. The frame would display properly tough.
  • Even if you load an URL that is in the same domain as the testRunner, the href will not reflect that change immediately, the second expect will fail (href will still equal 'about:blank') until the iframe has loaded, wich is way after your test already executed.

The following modified code uses Jasmine waitsFor() and runs() to account for the last problem. It will wait for 1000ms for the condition to be met, allowing the iframe to finish loading. I left your original spec inside the wait() block, however the waitsFor will also fail if there is a timeout.

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:');
    });
  });
});

Note that I also used 'about:' (withouth the 'blank'), as is the only -other- URL I know that won't throw an exception. However, it would be a good idea to use something else, maybe a pair of static fixture files in the same domain.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top