Pipecity
Pipecity

Reputation: 73

Mock XMLHttpRequest using jasmine-ajax gives jasmine.ajax = undefined

I'm trying to mock a XMLHttpRequest in a unit test using jasmine-ajax. I have used Aurelia CLI to generate my application and I'm using Karma as the unit test runner.

For the unit test I have tried importing 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:

TypeError: jasmine_ajax__WEBPACK_IMPORTED_MODULE_0__.jasmine is undefined in test/karma-bundle.js line 3146 > eval (line 7)

I have found that there is a type definition for jasmine-ajax that I have installed with

npm i @types/jasmine-ajax

I then removed the import statement of jasmine-ajax.This resulted in the following error:

TypeError: jasmine.Ajax is undefined in test/karma-bundle.js line 3134 > eval (line 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,

Upvotes: 0

Views: 1099

Answers (1)

Pipecity
Pipecity

Reputation: 73

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.

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

Upvotes: 2

Related Questions