首页 > 解决方案 > Jasmine / Karma 无法正确加载 Fixture HTML

问题描述

我创建了一个简单的 Fixture HTML 和 Jasmine 测试。

   <div id="testid">A</div>

这是我的测试代码。

define(['jquery'], function($) {
    'use strict';

    describe("Jasmine Fixture Test", function() {

        beforeAll(function(done) {
            jasmine.Ajax.install();

            done();
        });

        afterAll(() => {
            jasmine.Ajax.uninstall();
        });

        beforeEach(function() {
        });

        it("Test Fixture", function(done) {
            loadFixtures('TestFixture.html');

            expect($('#jasmine-fixtures')).toHaveId('jasmine-fixtures');
            expect($( '#testid' )).toHaveId('testid');
            expect($( '#testid' )).toHaveText('A');
            expect(true).toBeTruthy();
            done();
        });
    });
});

调用 loadFixture 时没有错误。

我已将 html 夹具文件添加到以下目录中:

C:\Workspace\PLAN_BUILDER\branches\634623.1.0.0\spec\javascripts\fixtures

我正在从以下位置运行“gradlew test”:

C:\Workspace\PLAN_BUILDER\branches\634623.1.0.0

我将调试语句添加到 karma-jasmine-jquery 库中,如下所示:

  jasmine.Fixtures.prototype.loadFixtureIntoCache_ = function (relativeUrl) {
      console.log(relativeUrl);
      console.log(this.makeFixtureUrl_(relativeUrl));
    var self = this
      , url = this.makeFixtureUrl_(relativeUrl)
      , htmlText = ''
      , request = $.ajax({
        async: false, // must be synchronous to guarantee that no tests are run before fixture is loaded
        cache: false,
        url: url,
        timeout: 2000,
        success: function (data, status, $xhr) {
            
            console.log(data);
            console.log(status);
            console.log($xhr.responseText);
          htmlText = $xhr.responseText
        }
      }).fail(function ($xhr, status, err) {
          console.log(err);
          console.log(status);
          throw new Error('Fixture could not be loaded: ' + url + ' (status: ' + status + ', message: ' + err.message + ')')
      }).always(function() {
    alert( "complete" );
  }
      );
console.log("after");
console.log(htmlText);

...

输出是这样的:

LOG LOG: 'TestFixture.html'
LOG LOG: 'spec/javascripts/fixtures/TestFixture.html'
LOG LOG: 'after'
LOG LOG: ''

因此,$.ajax 调用不会调用成功或失败方法回调,因此 htmlText 是空的。

谢谢你的建议。

标签: jqueryjasminekarma-jasminekarma-runnerjasmine-jquery

解决方案


问题是我在打电话

jasmine.Ajax.install();

loadFixtures('TestFixture.html');

我不知道 jasmine-jquery 正在使用 $.ajax 调用从磁盘加载夹具 html 文件。显然,jasmine-ajax 覆盖了 $.ajax 行为。

谢谢。


推荐阅读