Giter Club home page Giter Club logo

jasmine-ajax's Introduction

A JavaScript Testing Framework

Jasmine is a Behavior Driven Development testing framework for JavaScript. It does not rely on browsers, DOM, or any JavaScript framework. Thus it's suited for websites, Node.js projects, or anywhere that JavaScript can run.

Upgrading from Jasmine 4.x? Check out the upgrade guide.

Contributing

Please read the contributors' guide.

Installation

There are several different ways to install Jasmine, depending on your environment and how you'd like to use it. See the Getting Started page for details.

Usage

See the documentation site, particularly the Your First Suite tutorial for information on writing specs, and the FAQ.

Supported environments

Jasmine tests itself across popular browsers (Safari, Chrome, Firefox, and Microsoft Edge) as well as Node.

Environment Supported versions
Node 18, 20, 22
Safari 15-17
Chrome Evergreen
Firefox Evergreen, 102, 115
Edge Evergreen

For evergreen browsers, each version of Jasmine is tested against the version of the browser that is available to us at the time of release. Other browsers, as well as older & newer versions of some supported browsers, are likely to work. However, Jasmine isn't tested against them and they aren't actively supported.

To find out what environments work with a particular Jasmine release, see the release notes.

Maintainers

Maintainers Emeritus

Copyright (c) 2008-2019 Pivotal Labs
Copyright (c) 2008-2023 The Jasmine developers
This software is licensed under the MIT License.

jasmine-ajax's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jasmine-ajax's Issues

onFailure spy in phantom.js

If I have a test like this:

it("makes a failed request", function () {
    request.response(registrantGet.failure);
    parsedResponse = JSON.parse(request.responseText);
    expect(onfailure).toHaveBeenCalled();
    expect(parsedResponse.message).toBe("request failed");
});

It works in the browser, but not in phantom.js. Is this a known issue?

How to capture cross domain jQuery.ajax requests?

I´m trying to test a function which does a cross domain JSONP request. The request is not being captured by jasmine-ajax as I expected and is actually sent.

Am I doing it wrong or is this a bug?

Requests for relative uri´s are being captured as expected.

describe("Widget", function(){
    beforeEach(function(){
        jasmine.Ajax.install();
    });

    it('should notify listeners when data is loaded', function(){
        spyOn(Widget, 'notify');
        Widget.request('foo');
        request = jasmine.Ajax.requests.mostRecent();
        request.response(TestResponses.simple.success);
        expect(Widget.notify).toHaveBeenCalledWith('foo.loaded', {foo: "bar"});
    });
});

var Widget = {
    notify = function(event, data){
        // ...
    },
    request = function(resource){
        $.ajax({
            dataType: "jsonp",
            url: 'http://www.example.com/' + resource,
            jsonpCallback: "rw_jsonp_callback",
            success: function(jqXHR){
                Widget.notify(event, jqXHR);
            }
        });
    }
}

var TestResponses = {
    simple: {
        success: {
            status: 200,
                responseText: 'rw_jsonp_callback({"foo":"bar"})'
        }
    }
}

Do you guys support Ajax Post method

We are using Jasmine-ajax and seems like all our GET requests are being intercepted but Post calls are not.

Is there a way to intercept POST calls? any work around?

Please let us know,

Thanks,

Provide way to programmatically return data for AJAX requests, instead of doing it per test

It would be nice if I could pass jasmine-ajax a function which takes the URL, method and data as arguments, and allows me to programmatically decide what to return per AJAX call, without having to capture the most recent AJAX call and manually provide a response in my tests.

Issue #35 comes closer, since now I can pull out a request based on the URL, but it's still not optimal.

Fake Request data method does not handle nested data

If you use $.ajax to send nested data, or arrays of data, the data function on FakeXMLHttpRequest reformats the data unexpectedly. Try running the jasmine spec pasted below with jasmine-ajax installed...

it("returns the data object given to $.ajax", function() {
var data = {
foo: "bar",
things: ["1", "2"],
nest: { birds: { swallows: "unladen"}}
};
$.ajax({
url: "fake",
dataType: 'json',
data: data,
type: "POST"
});
var request = jasmine.Ajax.requests.mostRecent();
expect(request.data()).toEqual(data);
});

jQuery converts the data to a string using the $.param function. This is mildly annoying to reverse correctly. The jasmine-ajax data function handles the simplest cases, but you actually need something like https://github.com/chrissrogers/jquery-deparam/blob/master/jquery-deparam.js to do it right. jquery-deparam requires jquery, so I don't have a pull request for you, but it would be nice to have.

getAllResponseHeaders() should have a trailing CRLF

I ran into this issue when using jasmine-ajax v2.99.0 with superagent v0.21.0. The issue happens when you use respondWith that has responseHeaders -- the last header will get stripped by superagent.

So when you do the following:

jasmine.Ajax.requests.mostRecent().respondWith( {
  status: 200,
  responseHeaders: {
    allow: 'GET'
  }
});

In jasmine-ajax's fakeRequest.js, line 215, getAllResponseHeaders() returns the headers array joined by CRLF. When parsing the headers, superagent splits on CRLF and then pops the last entry with a comment "trailing CRLF".

The end result being that when you use jasmine-ajax with superagent, the last header gets stripped.

Looking at the actual spec, it doesn't say anything about requiring a trailing CRLF:

Return all response headers, excluding headers that are a case-insensitive match for Set-Cookie or Set-Cookie2, as a single string, with each header line separated by a U+000D CR U+000A LF pair, excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE pair.

However, all major browsers I tested (Chrome, IE, Firefox) all include the trailing CRLF, so it might be worth staying consistent.

As a workaround, you can include an extra dummy header.

Jasmine-Ajax with Node.js + CommonJS says getJasmineRequireObj undefined

I am testing the front end of a Backbone.js app using Node.js command line tools and CommonJS module loading. I used NPM to install Jasmine per the documentation and jasmine init to set up my project. Whenever I try to require Jasmine-Ajax, I get this exception:

/home/dana/Development/sandbox/node_modules/jasmine-ajax/lib/mock-ajax.js:33
getJasmineRequireObj().ajax = function(jRequire) {
^
ReferenceError: getJasmineRequireObj is not defined
    at Object. (/home/dana/Development/sandbox/node_modules/jasmine-ajax/lib/mock-ajax.js:33:1)
    at Module._compile (module.js:446:26)
    at Object.Module._extensions..js (module.js:464:10)
    at Module.load (module.js:341:32)
    at Function.Module._load (module.js:296:12)
    at Module.require (module.js:351:17)
    at require (module.js:370:17)
    at Object. (/home/dana/Development/sandbox/spec/protectedResourceSpec.js:3:1)
    at Module._compile (module.js:446:26)
    at Object.Module._extensions..js (module.js:464:10)

Something I read suggested this problem could be avoided by simply including mock-ajax.js in my Jasmine helpers directory, but when I did that, I repeatedly got errors like this:

Failures:
1) Protected Resource returns its token
  Message:
    TypeError: Cannot read property 'install' of undefined
  Stack:
    TypeError: Cannot read property 'install' of undefined
        at Object. (/home/dana/Development/sandbox/spec/protectedResourceSpec.js:14:17)
  Message:
    TypeError: Cannot read property 'token' of undefined
  Stack:
    TypeError: Cannot read property 'token' of undefined
        at Object. (/home/dana/Development/sandbox/spec/protectedResourceSpec.js:27:20)

(token is a property of my model.)

Am I correct in concluding that this plugin cannot be used in the Node environment/with CommonJS? (I am using jsdom for the window context.) If not, I'd be very grateful for any suggestions you have.

Asynchronous stub requests not working with jQuery 2.x

HI,

I created a test to mimic two rapid fire AJAX requests to the same server, however the requests are no longer executed in an asynchronous fashion after updating to jQuery 2.1.3. You can see the issue here on JSFiddle. The console will provide the order of events.

In the previous release of jQuery I was using (1.11.0), 'xhr.onload()' was not declared before the request was stubbed by Jasmine. As a result, upon reaching the 'this.events.load()' line within the 'respondWith' function, nothing was executed. It wasn't until the request was returned to jQuery with a 'readyState = 4' that the 'onload' callback was referenced within a setTimeout function without a defined time value.

My Fix:
With the latest jQuery release, xhr.onload is defined before the request is stubbed by Jasmine thus when 'this.events.load()' is called within 'respondWith', the callback is immediately executed. To fix this, I added an 'if' and setTimeout within the wrapProgressEvent function as shown below:

  function wrapProgressEvent(xhr, eventName) {
    return function() {
      if (xhr[eventName]) {
        if (eventName == "onload") {
          setTimeout(xhr[eventName]);
        } else {
          xhr[eventName]();
        }
      }
    };
  }

Syntax error in README

See the first line.

beforeEach(function){
  // first load your fixtures
  loadFixtures('fixture.html');

  // then install the mock
  jasmine.Ajax.useMock();
});

Null function error when calling response() multiple times with jQuery 2.1.x

For jQuery 1.10 and under, things like jasmine.Ajax.mostRecent().response(resp) ; jasmine.Ajax.mostRecent().response(resp); execute without errors (and the second .response call is a no-op). Newer versions of jQuery, however, null out the onload function on an XHR once it is resolved, meaning that the second .response call throws an error when executing this.onload().

I'm not sure whether this is behavior that should actually be supported, but I've sometimes found it useful when writing shared tests which require an XHR to be resolved, and for which the XHR might or might not have already resolved by the time they're invoked. With newer versions of jQuery, these tests fail unless the .response call is wrapped in a conditional like

if (jasmine.Ajax.requests.mostRecent().statusText === 'abort' || jasmine.Ajax.requests.mostRecent().readyState !== 0) {
  jasmine.Ajax.request.mostRecent().response(resp);
}

Support for "onerror" event

There's support for XMLHttpRequest.onload but it doesn't seem there's any support for mocking the onerror callback.

FakeXMLHttpRequest.data destroys the order of values.

Calling the the data method sorts the values as they are parsed out of the string destroying the original order of the values. The spec states this as desired behaviour. I do not understand why anyone would want this.

If you are passing matched arrays this destroys the the data.

Sending:

"key[]=a&key[]=b&value[]=22&value[]=1"

results in a return value from the data method of:

{ "key[]": ["a", "b"], "value[]": ["1", "22"] }

I have never come across any software that sorts POST or GET data in this way. Certainly all server side frameworks I've used go out of their way to maintain the order when parsing the raw http request.

I welcome discussion on the decision to sort the data values. Perhaps I am misunderstanding the purpose of the data method.

TypeError: Cannot read property 'install' of undefined

I have a Rails setup with Teaspoon (which runs Jasmine 1.3.1) and CoffeeScript. I have placed the mock-ajax.js (1.3.1) in my helpers directory. I have verified that the folder is included in jasmine.yml. On my jasmine.Ajax.install()call, I am greeted with TypeError: Cannot read property 'install' of undefined. I've tried placing the file inside support instead, I've tried including it as a require in the Jasmine spec helper. I've tried the 1.3.1 instructions and end up with a similar error (TypeError: Cannot read property 'useMock' of undefined). It seems as though mock-ajax.js is not even been loaded and I cannot figure out why. Anyone?

Uninstall should clear requests/stubs.

I was surprised that uninstall doesn't clear requests and stubs.There's a clear workaround in that I can choose to do this myself, but I would expect uninstall to basically give me a fresh instance. I can't really think of a case where I would want either to be preserved between tests.

I mention it only because I'm guessing in may be incidental -- if it's intentional I'm fine with clearing them myself I suppose, since it's just a few lines in my spec_helper.js.

Support addEventListener

Trying to call addEventListener on FakeXMLHttpRequest fails in all browsers with a similar error (the below one comes from Firefox):

TypeError: 'addEventListener' called on an object that does not implement interface EventTarget.

Would it be possible to support EventTarget interface (probably via CustomEvent - see http://stackoverflow.com/questions/20835768/addeventlistener-on-custom-object)?

This issue prevents using addEventListener("load", ...) on mocked XHR and also breaks other libraries that rely on it (e.g. Polymer in any browser other than Chrome).

request `response` is overloaded and can cause issues

Hi, I've run into a problem using the xhr library and testing it with jasmine-ajax. The xhr library looks for a response on the xhr and returns that as the body here. This to me looks like a perfectly valid choice since response is defined in XMLHttpRequest here.

My problem occurs when trying to use jasmine-ajax to specify a response. Instead of getting the body, the (jasmine-ajax) response function is returned, which is not correct.

Would it be possible to rename the FakeXMLHttpRequest response function to something that won't conflict? respondWith is one off the top of my head.

I currently get around this by monkey-patching the response (in case anyone else comes across this issue):

beforeEach(function(){
  jasmine.Ajax.install();
  monkeyPatchedRequest = new XMLHttpRequest();
  monkeyPatchedRequest.Response = monkeyPatchedRequest.response;
  monkeyPatchedRequest.response = undefined;
  // use monkeyPatchedRequest in your tests
})

Cannot stub when using JSON data

Hi,
I have tried to mock/stub my ajax call, but it looks like it only works with text. When I tried to set response with object then my done callback is not called:

jasmine.Ajax.stubRequest('/some_url/1').andReturn({
      //"responseText": response ,
     "response": response,
      "status": 200
    });

, but when I set responseText with object then it is called, but the responseJSON is not set, when debug response in FF

responseJSON undefined
status 200
statusText "success"

Am I doing something wrong or it is an issue?

I am using Jasmine 2.1.3 and latest version of jasmine-ajax (honestly I cannot figure it out where I can find version I am using...;-), I've just downloaded mock-ajax.js from link in documentation in github)

object is not a function after calling jQuery abort

jQuery sets xhr.onload and xhr.onerror to null after calling xhr.abort() which causes MockAjax to throw an error.

FakeXMLHttpRequest tries to call this.onload() during a FakeXMLHttpRequest.response() call, but the onload method is no longer set to an empty function which causes the error.

TypeError: object is not a function
    at FakeXMLHttpRequest.extend.response (../bower_components/jasmine-ajax/lib/mock-ajax.js:259:14)

Issue in jasmine-ajax installation

npm WARN git config --get remote.origin.url returned wrong result (git://github.com/pivotal/jasmine-ajax)
npm ERR! git clone git://github.com/pivotal/jasmine-ajax Cloning into bare repository 'C:\Users\le\AppData\Roaming\npm-cache_git-remotes\git-github-com-pivotal-jasmine-ajax-8282d883'...
npm ERR! git clone git://github.com/pivotal/jasmine-ajax fatal: unable to connect to github.com:
npm ERR! git clone git://github.com/pivotal/jasmine-ajax github.com[0: 192.30.252.130]: errno=No error
npm ERR! Error: Command failed: Cloning into bare repository 'C:\Users\le\AppData\Roaming\npm-cache_git-remotes\git-github-com-pivotal-jasmine-ajax-8282d883'...
npm ERR! fatal: unable to connect to github.com:
npm ERR! github.com[0: 192.30.252.130]: errno=No error
npm ERR!
npm ERR!
npm ERR! at ChildProcess.exithandler (child_process.js:647:15)
npm ERR! at ChildProcess.emit (events.js:98:17)
npm ERR! at maybeClose (child_process.js:755:16)
npm ERR! at Process.ChildProcess._handle.onexit (child_process.js:822:5)
npm ERR! If you need help, you may report this entire log,
npm ERR! including the npm and node versions, at:
npm ERR! http://github.com/npm/npm/issues

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "d:\Tools\Nodejs\node.exe" "d:\Tools\Nodejs\node_modules\npm\bin\npm-cli.js" "install" "karma-jasmine-ajax"
npm ERR! cwd d:\workspace\token_js
npm ERR! node -v v0.10.29
npm ERR! npm -v 1.4.14
npm ERR! code 128

Deferred callbacks not firing with jQuery 1.9.1

Hi,

First of all thanks for jasmine-ajax.

I have a test suite for a Backbone project which includes some tests
leveraging jasmine-ajax. When I updated jQuery to 1.9.1 version the
tests started failing. After some investigation, turns out that the XHR
callbacks aren't firing after calling FakeXMLHTTPRequest.response.

A minimal test case to reproduce the issue:

describe('Success callback not executing', function() {
    it('runs the callback after getting a response', function() {                                                                       
      jasmine.Ajax.useMock();                                                                                                           

      var callback = jasmine.createSpy();                                                                                               
      $.get('/foo').done(callback);                                                                                                     

      var request = mostRecentAjaxRequest();                                                                                            
      request.response({ status: 200, responseText: 'Foo' });                                                                           

      expect(callback).toHaveBeenCalled();                                                                                              
    });
});

I'm using the latest development version. Am I missing something?

Compatibility with jQuery 1.5

I've just upgraded to jQuery 1.5. Apparently, the jQuery mock-ajax doesn't work anymore. I've got my spec_helper (in CoffeeScript) like I used to for jQuery 1.4:

spyOn(jQuery.ajaxSettings, 'xhr').andCallFake ->
  newXhr = new FakeXMLHttpRequest()
  ajaxRequests.push(newXhr)
  newXhr

Now, everytime I set a response, like:
request = mostRecentAjaxRequest()
request.response responseText: 'My response'

I get the following error:
TypeError: xhr.getAllResponseHeaders is not a function in jquery.js (line 7207)

Apparently that function was added to jQuery 1.5, related to the jqXHR stuff. I've tried to investage further, but couldn't find a fix.

ExtJS support

Would be cool to integrate jasmine-ajax in my jasmine ExtJS tests ...

Unable to verify JSON POST request data in test

To outline problem, I added a test that I expected to succeed but currently fails.

Using the situation as described in the test, any browser I tested will post JSON to a webservice correctly. When I try asserting that the data submitted in the request is actually what I expected using jasmine-ajax, it's not equal to what a browser actually submits.
The same problem is seen when trying to validate any FormData.

--- /tmp/fake-xml-http-request-spec.js  2014-04-08 13:20:24.319475806 +0200
+++ fake-xml-http-request-spec.js       2014-04-08 13:20:45.555475947 +0200
@@ -107,15 +107,24 @@
   describe("data", function() {
     beforeEach(function() {
       xhr.open("POST", "http://example.com?this=that");
-      xhr.send('3+stooges=shemp&3+stooges=larry%20%26%20moe%20%26%20curly&some%3Dthing=else+entirely');
     });

     it("should return request params as a hash of arrays with values sorted alphabetically", function() {
+      xhr.send('3+stooges=shemp&3+stooges=larry%20%26%20moe%20%26%20curly&some%3Dthing=else+entirely');
       var data = xhr.data();
       expect(data['3 stooges'].length).toEqual(2);
       expect(data['3 stooges'][0]).toEqual('larry & moe & curly');
       expect(data['3 stooges'][1]).toEqual('shemp');
       expect(data['some=thing']).toEqual(['else entirely']);
     });
+
+    it("should return request params as stringified JSON", function() {
+      xhr.setRequestHeader('Content-Type', 'application/json');
+      var stringified = JSON.stringify({id: 5});
+      console.info(stringified);
+      xhr.send(stringified);
+      var data = xhr.data();
+      expect(data).toEqual('{"id":5}');
+    });
   });
 });

Support for XMLHttpRequest2

It would be nice to have to also have the mock handle XMLHttpRequest2. I have a need on a project to get binary data so I can't really use regular ajax.

The mock should be made to handle the generic cases for now, and potentially extended to handle all the features of ajax2 requests.

If I have time I'll send a pull request with the support for this.

Ability to pass-through requests

In my test, I need to mock a certain XHR request but pass-though all the other requests. Currently, it is only possible if I run jasmine.Ajax.install() / jasmine.Ajax.uninstall() between requests. But this requires me to change files that make the requests.

It would be much cleaner if I could set up FakeXMLHttpRequest to pass-through requests on a certain condition.

WDYT?

Object #<FakeXMLHttpRequest> has no method 'data'

Hi

This is the first time I use jasmine-ajax library, I'm following your example on the README, when I run the spec, it throw out TypeError: Object #<FakeXMLHttpRequest> has no method 'data'

here is my code.

it('should be success', function(){

      expect(request.method).toBe('POST');
      expect(request.data()).toEqual({latLng: ['40.019461, -105.273296']});
    });

And I checkout the source code and I do not found data method on the request object, or it may be its coming from the parent object.

do I did something wrong? please help.

Jasmine mock ajax calls not working in IE.

Hi,

I tried writing a spec that allows Ajax calls to be mocked out. The test case works perfectly fine on browsers like Chrome and Firefox. But I am facing some issues when I run the test case on IE. This issue arises when the normal Ajax calls are made using jQuery Ajax.

I get an error in IE as follows:

TypeError: Unable to get value of the property 'response': object is null or undefined.

The test case that I have written is as follows

describe("mocking ajax", function() {
    /**
     * When you want to mock out all ajax calls across an entire suite, 
     *  use `install()` in a `beforeEach`.
     */
    beforeEach(function() {
      jasmine.Ajax.install();
    });

    /**
     * Because jasmine-ajax stubs out the global XMLHttpRequest for the page, 
     * you'll  want to `uninstall()` in an `afterEach` so specs or 
     * setup that expect to  make a real ajax request can.
     */
    afterEach(function() {
      jasmine.Ajax.uninstall();
    });

    it("specifying response when you need it", function() {
      var doneFn = jasmine.createSpy("success");

      /**
       * Make your requests as normal.
       * Jasmine-Ajax mocks out your request at the XMLHttpRequest object, 
       * so should be compatible with other libraries that do ajax requests.
       */
      var jqxhr = $.ajax({
        url :"/any/service",
        success : function(data){
          doneFn(data);
        }
      });

      /**
       * At this point the ajax request won't have returned, 
       * so any assertions about intermediate states (like spinners) 
       * can be run here.
       */
      expect(doneFn).not.toHaveBeenCalled();

      /**
       * Now we tell the request what it's response should look like
       */
      jasmine.Ajax.requests.mostRecent().response({
        "status": 200,
        "contentType": 'text/plain',
        "responseText": 'awesome response'
      });

      /**
       * Now that we've told the request to respond, our callback gets called.
       */
      expect(doneFn).toHaveBeenCalledWith('awesome response');
    });

});

Any help regarding this issue is appreciated.
Thanks in advance!

async false

Hi

I have a problem getting jasmine-ajax to work when a jQuery ajax call is done with the async property set to false.
Switching back to async fixes this, but this call is required to be synchronous in our code.

Any suggestions?

mostRecent().responseTimeout does not pass through statusText of 'timeout'

Failing spec as follows:

    describe('mocking ajax timeout', function() {

        it('should pass "timeout" statusText correctly', function () {
            jasmine.Ajax.install();
            jasmine.clock().install();

            $(document).ajaxError(function (event, jqxhr) {
                expect(jqxhr.statusText).toBe('timeout');
            });

            $.ajax({
                url: 'a/test/url',
                success: $.noop,
                error: $.noop
            });

            jasmine.Ajax.requests.mostRecent().responseTimeout();

            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (this.readyState == this.DONE)
                    expect(this.statusText).toBe('timeout');
            };

            xhr.open("GET", "/some/cool/url");
            xhr.send();

            jasmine.Ajax.requests.mostRecent().responseTimeout();
        });
    });

My spec is using jQuery 1.11.1 (which of course adds a layer of complexity) but even with just native XMLHttpRequest this doesn't seem quite right.

Will attempt a pull request with a simple fix shortly.

Any thoughts greatly appreciated?

Many thanks,
Mike Godfrey.

Twitter API returns JSONP - tests work, but app does not

The TwitterAPISpec passes all tests. However, the JQuery example application fails to work - Firebug reports empty response.

If you change the TwitterAPI.js - around line12 - to add : dataType: "JSONP" - then the sample application works OK. But TwitterAPISpec tests report 16 failures.

'response' method conflicts with code under test

Trying to write some unit tests with jasmine-ajax and 'angular-file-upload' I'm finding that the jasmine-ajax response method used to set the response data is conflicting with code in angular-file-upload which wants to do 'xhr.response' and then parse that response data. In my tests this field is the stringified version of jasmine-ajax response() function used to construct the mock response data.

Looking at Mozilla Dev Network it looks like both response and responseText are valid fields in the xhr object, though response may support a wider range of data types.

Other than changing either jasmine-ajax to use 'setResponse' (an API breaking change) instead of 'response' or changing angular-file-upload to only look at responseText (and possibly missing other data types) are there any other workarounds ?

AJAX immediately returning an error in IE10

I have succesfully mocked out AJAX calls in several tests when run in FireFox.

However, when running in IE10, after calling $.ajax control passes straight to the error callback.

The first parameter is { readyState: 0, status: 0. statusText: "Error: The system cannot locate the resource specified." } and the second parameter is a similar message.

The third parameter has the message again, a "number" of -2146697211 and a stack of:

Error: The system cannot locate the resource specified.
 at send (file:///x/Scripts/jquery-1.10.2.js:8720:6)
 at ajax (file:///x/Scripts/jquery-1.10.2.js:8150:5)
 at DoSearch (file:///x/Scripts/lkg-multilicense.js:155:17)
 at Anonymous function (file:///x/Web/Jasmine/spec/MultiLicenseSpec.js:843:25)
 at attemptSync (file:///x/Web/Jasmine/lib/jasmine-2.0.2/jasmine.js:1620:9)
 at run (file:///x/Web/Jasmine/lib/jasmine-2.0.2/jasmine.js:1608:9)
 at execute (file:///x/Web/Jasmine/lib/jasmine-2.0.2/jasmine.js:1595:5)
 at queueRunnerFactory (file:///x/Web/Jasmine/lib/jasmine-2.0.2/jasmine.js:508:7)
 at execute (file:///x/Web/Jasmine/lib/jasmine-2.0.2/jasmine.js:295:5)
 at Anonymous function (file:///x/Web/Jasmine/lib/jasmine-2.0.2/jasmine.js:1834:31)

I'm using Jasmine 2.0.2 and the currently-28-day-old version of mock-ajax.js.

Allow partial URL matching or allow use of a function to determine match

When you create a stub it wants a full URL match but in most cases it's enough to do a partial match and often the environment your developing the unit tests on will be a different server than where the continuous integration is hosted so the URL will be different on a different server.

If you add an option to the stub creation process to allow a partial URL match it would make it much more flexible.

overrideMimeType thows 'Illegal invocation' on FakeXMLHttpRequest

It looks like XMLHttpRequest.overrideMimeType has some reference to this which gets messed up when it's called on FakeXMLHttpRequest. overrideMimeType is just extended into FakeXMLHttpRequest. Perhaps it should stubbed out in some way?

var realReq = new XMLHttpRequest();
realReq.overrideMimeType('text/plain');
jasmine.Ajax.install();
var fakeReq = new XMLHttpRequest();
fakeReq.overrideMimeType('text/plain');
>>> TypeError: Illegal invocation

I'm getting this on Chrome 36.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.