【问题标题】:Mock XMLHttpRequest using jasmine-ajax gives jasmine.ajax = undefined使用 jasmine-ajax 模拟 XMLHttpRequest 给出 jasmine.ajax = undefined
【发布时间】:2019-03-15 12:58:08
【问题描述】:

我正在尝试使用 jasmine-ajax 在单元测试中模拟 XMLHttpRequest。我使用 Aurelia CLI 来生成我的应用程序,并且我使用 Karma 作为单元测试运行器。

对于单元测试,我尝试导入 jasmine-ajax:

import * as jasmine from 'jasmine-ajax';

describe('when calling the API', () => {
  beforeEach(() => {
    jasmine.Ajax.install();
  });

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

  it('then it should get an answer back', () => {
    var doneFn = jasmine.createSpy("success");

    var xhr= new XMLHttpRequest();
    xhr.onreadystatechange = function(args) {
      if(this.readyState == this.DONE) {
        doneFn(this.responseText);
      }
    };

    xhr.open("GET", "https://someaddress.net/api/plans");
    xhr.send();

    expect(jasmine.Ajax.requests.mostRecent().url).toBe("https://someaddress.net/api/plans");
    expect(doneFn).not.toHaveBeenCalled();

    jasmine.Ajax.requests.mostRecent().respondWith({
      "status":200,
      "contentType": 'text/plain',
      "responseText": 'awesome response'
    });

    expect(doneFn).toHaveBeenCalledWith('awesome response');

  });
});

使用 Karma 运行测试时,我得到:

TypeError: jasmine_ajax__WEBPACK_IMPORTED_MODULE_0__.jasmine 是 在 test/karma-bundle.js 第 3146 行 > eval(第 7 行)中未定义

我发现我已经安装了 jasmine-ajax 的类型定义

npm i @types/jasmine-ajax

然后我删除了 jasmine-ajax 的 import 语句。这导致了以下错误:

TypeError: jasmine.Ajax is undefined in test/karma-bundle.js line 3134 > eval (line 3)

那我做错了什么?

我正在使用 jasmine 3.3.9、jasmine-ajax 3.4.0、karma 4.0.1、typescript 2.9.2 和 webpack 4.4.25,

【问题讨论】:

  • 你使用哪个命令来运行测试
  • 我正在使用'au karma'

标签: typescript webpack jasmine karma-jasmine jasmine-ajax


【解决方案1】:

安装 karma-jasmine-ajax (https://github.com/IDCubed/karma-jasmine-ajax) 并将“jasmine-ajax”添加到 karma.conf.js 中的框架数组后,它开始工作。

module.exports = function(config) {
  config.set({
    frameworks: ['jasmine-ajax', 'jasmine']
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-13
    相关资源
    最近更新 更多