简体   繁体   English

使用jasmine-ajax模拟XMLHttpRequest给出jasmine.ajax = undefined

[英]Mock XMLHttpRequest using jasmine-ajax gives jasmine.ajax = undefined

I'm trying to mock a XMLHttpRequest in a unit test using jasmine-ajax. 我正在尝试在使用jasmine-ajax的单元测试中模拟XMLHttpRequest。 I have used Aurelia CLI to generate my application and I'm using Karma as the unit test runner. 我已经使用Aurelia CLI生成了我的应用程序,并且正在使用Karma作为单元测试运行器。

For the unit test I have tried importing jasmine-ajax: 对于单元测试,我尝试导入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');

  });
});

When running the test with Karma I get: 使用Karma进行测试时,我得到:

TypeError: jasmine_ajax__WEBPACK_IMPORTED_MODULE_0__.jasmine is undefined in test/karma-bundle.js line 3146 > eval (line 7) TypeError:jasmine_ajax__WEBPACK_IMPORTED_MODULE_0 __。jasmine在test / karma-bundle.js第3146行> eval(第7行)中未定义

I have found that there is a type definition for jasmine-ajax that I have installed with 我发现我已经安装了jasmine-ajax的类型定义

npm i @types/jasmine-ajax npm我@ types / jasmine-ajax

I then removed the import statement of jasmine-ajax.This resulted in the following error: 然后我删除了jasmine-ajax的import语句,这导致以下错误:

TypeError: jasmine.Ajax is undefined in test/karma-bundle.js line 3134 > eval (line 3) TypeError:jasmine.Ajax在test / karma-bundle.js第3134行> eval(第3行)中未定义

So what am I doing incorrect? 那我在做什么错呢?

I am using jasmine 3.3.9, jasmine-ajax 3.4.0, karma 4.0.1, typescript 2.9.2 and webpack 4.4.25, 我正在使用茉莉花3.3.9,茉莉花ajax 3.4.0,业力4.0.1,打字稿2.9.2和webpack 4.4.25,

After installing karma-jasmine-ajax ( https://github.com/IDCubed/karma-jasmine-ajax ) and adding 'jasmine-ajax' to the frameworks array in karma.conf.js it started working. 在安装karma-jasmine-ajax( https://github.com/IDCubed/karma-jasmine-ajax )并将'jasmine-ajax'添加到karma.conf.js中的frameworks数组后,它开始工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM