jquery_mockjax_rails 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +9 -0
  3. data/.rspec +1 -0
  4. data/.ruby-gemset +1 -0
  5. data/.ruby-version +1 -0
  6. data/.travis.yml +8 -0
  7. data/Gemfile +3 -0
  8. data/Gemfile.lock +152 -0
  9. data/MIT-LICENSE +20 -0
  10. data/README.md +62 -0
  11. data/Rakefile +11 -0
  12. data/jquery_mockjax_rails.gemspec +26 -0
  13. data/lib/jquery_mockjax_rails.rb +8 -0
  14. data/lib/jquery_mockjax_rails/engine.rb +8 -0
  15. data/lib/jquery_mockjax_rails/helper.rb +7 -0
  16. data/lib/jquery_mockjax_rails/jquery_mockjax_middleware.rb +24 -0
  17. data/lib/jquery_mockjax_rails/jquery_mockjax_rails.rb +25 -0
  18. data/lib/jquery_mockjax_rails/rspec_integration.rb +9 -0
  19. data/lib/jquery_mockjax_rails/version.rb +3 -0
  20. data/spec/dummy/Rakefile +7 -0
  21. data/spec/dummy/app/assets/javascripts/application.js +15 -0
  22. data/spec/dummy/app/assets/stylesheets/application.css +13 -0
  23. data/spec/dummy/app/controllers/application_controller.rb +3 -0
  24. data/spec/dummy/app/controllers/home_controller.rb +4 -0
  25. data/spec/dummy/app/helpers/application_helper.rb +2 -0
  26. data/spec/dummy/app/views/home/index.html.erb +2 -0
  27. data/spec/dummy/app/views/layouts/application.html.erb +14 -0
  28. data/spec/dummy/config.ru +4 -0
  29. data/spec/dummy/config/application.rb +65 -0
  30. data/spec/dummy/config/boot.rb +10 -0
  31. data/spec/dummy/config/database.yml +25 -0
  32. data/spec/dummy/config/environment.rb +5 -0
  33. data/spec/dummy/config/environments/test.rb +37 -0
  34. data/spec/dummy/config/initializers/backtrace_silencers.rb +7 -0
  35. data/spec/dummy/config/initializers/inflections.rb +15 -0
  36. data/spec/dummy/config/initializers/mime_types.rb +5 -0
  37. data/spec/dummy/config/initializers/secret_token.rb +7 -0
  38. data/spec/dummy/config/initializers/session_store.rb +8 -0
  39. data/spec/dummy/config/initializers/wrap_parameters.rb +14 -0
  40. data/spec/dummy/config/locales/en.yml +5 -0
  41. data/spec/dummy/config/routes.rb +60 -0
  42. data/spec/dummy/lib/assets/.gitkeep +0 -0
  43. data/spec/dummy/log/.gitkeep +0 -0
  44. data/spec/dummy/public/favicon.ico +0 -0
  45. data/spec/dummy/script/rails +6 -0
  46. data/spec/requests/assets_spec.rb +11 -0
  47. data/spec/requests/home_spec.rb +18 -0
  48. data/spec/spec_helper.rb +21 -0
  49. data/spec/support/capybara.rb +2 -0
  50. data/spec/support/integration_helper.rb +5 -0
  51. data/vendor/assets/javascripts/jquery.mockjax.js +580 -0
  52. metadata +192 -0
@@ -0,0 +1,13 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the top of the
9
+ * compiled file, but it's generally better to create a new file per style scope.
10
+ *
11
+ *= require_self
12
+ *= require_tree .
13
+ */
@@ -0,0 +1,3 @@
1
+ class ApplicationController < ActionController::Base
2
+ protect_from_forgery
3
+ end
@@ -0,0 +1,4 @@
1
+ class HomeController < ApplicationController
2
+ def index
3
+ end
4
+ end
@@ -0,0 +1,2 @@
1
+ module ApplicationHelper
2
+ end
@@ -0,0 +1,2 @@
1
+ <h1>Home#index</h1>
2
+ <p>Find me in app/views/home/index.html.erb</p>
@@ -0,0 +1,14 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Dummy</title>
5
+ <%= stylesheet_link_tag 'application', :media => 'all' %>
6
+ <%= javascript_include_tag 'application' %>
7
+ <%= csrf_meta_tags %>
8
+ </head>
9
+ <body>
10
+
11
+ <%= yield %>
12
+
13
+ </body>
14
+ </html>
@@ -0,0 +1,4 @@
1
+ # This file is used by Rack-based servers to start the application.
2
+
3
+ require ::File.expand_path('../config/environment', __FILE__)
4
+ run Dummy::Application
@@ -0,0 +1,65 @@
1
+ require File.expand_path('../boot', __FILE__)
2
+
3
+ # Pick the frameworks you want:
4
+ require 'active_record/railtie'
5
+ require 'action_controller/railtie'
6
+ require 'action_mailer/railtie'
7
+ require 'active_resource/railtie'
8
+ require 'sprockets/railtie'
9
+ # require 'rails/test_unit/railtie'
10
+
11
+ Bundler.require(*Rails.groups)
12
+ require 'jquery_mockjax_rails'
13
+
14
+ module Dummy
15
+ class Application < Rails::Application
16
+ # Settings in config/environments/* take precedence over those specified here.
17
+ # Application configuration should go into files in config/initializers
18
+ # -- all .rb files in that directory are automatically loaded.
19
+
20
+ # Custom directories with classes and modules you want to be autoloadable.
21
+ # config.autoload_paths += %W(#{config.root}/extras)
22
+
23
+ # Only load the plugins named here, in the order given (default is alphabetical).
24
+ # :all can be used as a placeholder for all plugins not explicitly named.
25
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
26
+
27
+ # Activate observers that should always be running.
28
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
29
+
30
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
31
+ # Run 'rake -D time' for a list of tasks for finding time zone names. Default is UTC.
32
+ # config.time_zone = 'Central Time (US & Canada)'
33
+
34
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
35
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
36
+ # config.i18n.default_locale = :de
37
+
38
+ # Configure the default encoding used in templates for Ruby 1.9.
39
+ config.encoding = 'utf-8'
40
+
41
+ # Configure sensitive parameters which will be filtered from the log file.
42
+ config.filter_parameters += [:password]
43
+
44
+ # Enable escaping HTML in JSON.
45
+ config.active_support.escape_html_entities_in_json = true
46
+
47
+ # Use SQL instead of Active Record's schema dumper when creating the database.
48
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
49
+ # like if you have constraints or database-specific column types
50
+ # config.active_record.schema_format = :sql
51
+
52
+ # Enforce whitelist mode for mass assignment.
53
+ # This will create an empty whitelist of attributes available for mass-assignment for all models
54
+ # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
55
+ # parameters by using an attr_accessible or attr_protected declaration.
56
+ config.active_record.whitelist_attributes = true
57
+
58
+ # Enable the asset pipeline
59
+ config.assets.enabled = true
60
+
61
+ # Version of your assets, change this if you want to expire all your assets
62
+ config.assets.version = '1.0'
63
+ end
64
+ end
65
+
@@ -0,0 +1,10 @@
1
+ require 'rubygems'
2
+ gemfile = File.expand_path('../../../../Gemfile', __FILE__)
3
+
4
+ if File.exist?(gemfile)
5
+ ENV['BUNDLE_GEMFILE'] = gemfile
6
+ require 'bundler'
7
+ Bundler.setup
8
+ end
9
+
10
+ $:.unshift File.expand_path('../../../../lib', __FILE__)
@@ -0,0 +1,25 @@
1
+ # SQLite version 3.x
2
+ # gem install sqlite3
3
+ #
4
+ # Ensure the SQLite 3 gem is defined in your Gemfile
5
+ # gem 'sqlite3'
6
+ development:
7
+ adapter: sqlite3
8
+ database: db/development.sqlite3
9
+ pool: 5
10
+ timeout: 5000
11
+
12
+ # Warning: The database defined as 'test' will be erased and
13
+ # re-generated from your development database when you run 'rake'.
14
+ # Do not set this db to the same as development or production.
15
+ test:
16
+ adapter: sqlite3
17
+ database: db/test.sqlite3
18
+ pool: 5
19
+ timeout: 5000
20
+
21
+ production:
22
+ adapter: sqlite3
23
+ database: db/production.sqlite3
24
+ pool: 5
25
+ timeout: 5000
@@ -0,0 +1,5 @@
1
+ # Load the rails application
2
+ require File.expand_path('../application', __FILE__)
3
+
4
+ # Initialize the rails application
5
+ Dummy::Application.initialize!
@@ -0,0 +1,37 @@
1
+ Dummy::Application.configure do
2
+ # Settings specified here will take precedence over those in config/application.rb
3
+
4
+ # The test environment is used exclusively to run your application's
5
+ # test suite. You never need to work with it otherwise. Remember that
6
+ # your test database is 'scratch space' for the test suite and is wiped
7
+ # and recreated between test runs. Don't rely on the data there!
8
+ config.cache_classes = true
9
+
10
+ # Configure static asset server for tests with Cache-Control for performance
11
+ config.serve_static_assets = true
12
+ config.static_cache_control = 'public, max-age=3600'
13
+
14
+ # Log error messages when you accidentally call methods on nil
15
+ config.whiny_nils = true
16
+
17
+ # Show full error reports and disable caching
18
+ config.consider_all_requests_local = true
19
+ config.action_controller.perform_caching = false
20
+
21
+ # Raise exceptions instead of rendering exception templates
22
+ config.action_dispatch.show_exceptions = false
23
+
24
+ # Disable request forgery protection in test environment
25
+ config.action_controller.allow_forgery_protection = false
26
+
27
+ # Tell Action Mailer not to deliver emails to the real world.
28
+ # The :test delivery method accumulates sent emails in the
29
+ # ActionMailer::Base.deliveries array.
30
+ config.action_mailer.delivery_method = :test
31
+
32
+ # Raise exception on mass assignment protection for Active Record models
33
+ config.active_record.mass_assignment_sanitizer = :strict
34
+
35
+ # Print deprecation notices to the stderr
36
+ config.active_support.deprecation = :stderr
37
+ end
@@ -0,0 +1,7 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4
+ # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5
+
6
+ # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
7
+ # Rails.backtrace_cleaner.remove_silencers!
@@ -0,0 +1,15 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Add new inflection rules using the following format
4
+ # (all these examples are active by default):
5
+ # ActiveSupport::Inflector.inflections do |inflect|
6
+ # inflect.plural /^(ox)$/i, '\1en'
7
+ # inflect.singular /^(ox)en/i, '\1'
8
+ # inflect.irregular 'person', 'people'
9
+ # inflect.uncountable %w( fish sheep )
10
+ # end
11
+ #
12
+ # These inflection rules are supported but not enabled by default:
13
+ # ActiveSupport::Inflector.inflections do |inflect|
14
+ # inflect.acronym 'RESTful'
15
+ # end
@@ -0,0 +1,5 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Add new mime types for use in respond_to blocks:
4
+ # Mime::Type.register 'text/richtext', :rtf
5
+ # Mime::Type.register_alias 'text/html', :iphone
@@ -0,0 +1,7 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ # Your secret key for verifying the integrity of signed cookies.
4
+ # If you change this key, all old signed cookies will become invalid!
5
+ # Make sure the secret is at least 30 characters and all random,
6
+ # no regular words or you'll be exposed to dictionary attacks.
7
+ Dummy::Application.config.secret_token = '632739e971d2ab2b910fb94866bdfbb2012f88a4940b685173560872c0416e7e226cf135194087801e2772fa704492b247dcb4f5783f725e1ff1f92fefd3d43e'
@@ -0,0 +1,8 @@
1
+ # Be sure to restart your server when you modify this file.
2
+
3
+ Dummy::Application.config.session_store :cookie_store, key: '_dummy_session'
4
+
5
+ # Use the database for sessions instead of the cookie-based default,
6
+ # which shouldn't be used to store highly confidential information
7
+ # (create the session table with 'rails generate session_migration')
8
+ # Dummy::Application.config.session_store :active_record_store
@@ -0,0 +1,14 @@
1
+ # Be sure to restart your server when you modify this file.
2
+ #
3
+ # This file contains settings for ActionController::ParamsWrapper which
4
+ # is enabled by default.
5
+
6
+ # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
7
+ ActiveSupport.on_load(:action_controller) do
8
+ wrap_parameters format: [:json]
9
+ end
10
+
11
+ # Disable root element in JSON by default.
12
+ ActiveSupport.on_load(:active_record) do
13
+ self.include_root_in_json = false
14
+ end
@@ -0,0 +1,5 @@
1
+ # Sample localization file for English. Add more files in this directory for other locales.
2
+ # See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
3
+
4
+ en:
5
+ hello: 'Hello world'
@@ -0,0 +1,60 @@
1
+ Dummy::Application.routes.draw do
2
+ get "home/index"
3
+
4
+ # The priority is based upon order of creation:
5
+ # first created -> highest priority.
6
+
7
+ # Sample of regular route:
8
+ # match 'products/:id' => 'catalog#view'
9
+ # Keep in mind you can assign values other than :controller and :action
10
+
11
+ # Sample of named route:
12
+ # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
13
+ # This route can be invoked with purchase_url(:id => product.id)
14
+
15
+ # Sample resource route (maps HTTP verbs to controller actions automatically):
16
+ # resources :products
17
+
18
+ # Sample resource route with options:
19
+ # resources :products do
20
+ # member do
21
+ # get 'short'
22
+ # post 'toggle'
23
+ # end
24
+ #
25
+ # collection do
26
+ # get 'sold'
27
+ # end
28
+ # end
29
+
30
+ # Sample resource route with sub-resources:
31
+ # resources :products do
32
+ # resources :comments, :sales
33
+ # resource :seller
34
+ # end
35
+
36
+ # Sample resource route with more complex sub-resources
37
+ # resources :products do
38
+ # resources :comments
39
+ # resources :sales do
40
+ # get 'recent', :on => :collection
41
+ # end
42
+ # end
43
+
44
+ # Sample resource route within a namespace:
45
+ # namespace :admin do
46
+ # # Directs /admin/products/* to Admin::ProductsController
47
+ # # (app/controllers/admin/products_controller.rb)
48
+ # resources :products
49
+ # end
50
+
51
+ # You can have the root of your site routed with 'root'
52
+ # just remember to delete public/index.html.
53
+ # root :to => 'welcome#index'
54
+
55
+ # See how all your routes lay out with 'rake routes'
56
+
57
+ # This is a legacy wild controller route that's not recommended for RESTful applications.
58
+ # Note: This route will make all actions in every controller accessible via GET requests.
59
+ # match ':controller(/:action(/:id))(.:format)'
60
+ end
File without changes
File without changes
File without changes
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+ # This command will automatically be run when you run 'rails' with Rails 3 gems installed from the root of your application.
3
+
4
+ APP_PATH = File.expand_path('../../config/application', __FILE__)
5
+ require File.expand_path('../../config/boot', __FILE__)
6
+ require 'rails/commands'
@@ -0,0 +1,11 @@
1
+ require 'spec_helper'
2
+
3
+ describe 'static assets integration' do
4
+ before do
5
+ visit '/assets/jquery.mockjax.js'
6
+ end
7
+
8
+ it 'provides jquery.mockjax.js on the assets pipeline' do
9
+ page.text.should include 'MockJax - jQuery Plugin to Mock Ajax requests'
10
+ end
11
+ end
@@ -0,0 +1,18 @@
1
+ require 'spec_helper'
2
+
3
+ describe "Stub ajax request", js: true do
4
+ let(:message) { 'my custom message' }
5
+ let(:api_path) { '/api/path' }
6
+
7
+ before do
8
+ stub_ajax url: api_path, responseText: { message: message }
9
+ visit home_index_path
10
+ end
11
+
12
+ it 'stubs the ajax request and returns the correct message' do
13
+ page.execute_script("$.getJSON('#{api_path}', function(data) { $('body').append(data.message) })")
14
+ wait_until do
15
+ page.has_content?(message)
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,21 @@
1
+ # This file is copied to spec/ when you run 'rails generate rspec:install'
2
+ ENV["RAILS_ENV"] ||= 'test'
3
+ require File.expand_path('../dummy/config/environment', __FILE__)
4
+ require 'rspec/rails'
5
+ require 'rspec/autorun'
6
+ require 'capybara'
7
+ require 'capybara/rails'
8
+ require 'capybara/rspec'
9
+ require 'capybara/dsl'
10
+ require 'jquery_mockjax_rails'
11
+
12
+ # Requires supporting ruby files with custom matchers and macros, etc,
13
+ # in spec/support/ and its subdirectories.
14
+ Dir[File.expand_path('../support/**/*.rb', __FILE__)].each { |f| require f }
15
+ Rails.backtrace_cleaner.remove_silencers!
16
+ RSpec.configure do |config|
17
+ config.fixture_path = "#{::Rails.root}/spec/fixtures"
18
+ config.use_transactional_fixtures = true
19
+ config.infer_base_class_for_anonymous_controllers = false
20
+ config.include Capybara::DSL
21
+ end
@@ -0,0 +1,2 @@
1
+ require 'capybara/poltergeist'
2
+ Capybara.javascript_driver = :poltergeist
@@ -0,0 +1,5 @@
1
+ def wait_until
2
+ Timeout.timeout(Capybara.default_wait_time) do
3
+ sleep(0.1) until yield == true
4
+ end
5
+ end
@@ -0,0 +1,580 @@
1
+ /*!
2
+ * MockJax - jQuery Plugin to Mock Ajax requests
3
+ *
4
+ * Version: 1.5.2
5
+ * Released:
6
+ * Home: http://github.com/appendto/jquery-mockjax
7
+ * Author: Jonathan Sharp (http://jdsharp.com)
8
+ * License: MIT,GPL
9
+ *
10
+ * Copyright (c) 2011 appendTo LLC.
11
+ * Dual licensed under the MIT or GPL licenses.
12
+ * http://appendto.com/open-source-licenses
13
+ */
14
+ (function($) {
15
+ var _ajax = $.ajax,
16
+ mockHandlers = [],
17
+ mockedAjaxCalls = [],
18
+ CALLBACK_REGEX = /=\?(&|$)/,
19
+ jsc = (new Date()).getTime();
20
+
21
+
22
+ // Parse the given XML string.
23
+ function parseXML(xml) {
24
+ if ( window.DOMParser == undefined && window.ActiveXObject ) {
25
+ DOMParser = function() { };
26
+ DOMParser.prototype.parseFromString = function( xmlString ) {
27
+ var doc = new ActiveXObject('Microsoft.XMLDOM');
28
+ doc.async = 'false';
29
+ doc.loadXML( xmlString );
30
+ return doc;
31
+ };
32
+ }
33
+
34
+ try {
35
+ var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );
36
+ if ( $.isXMLDoc( xmlDoc ) ) {
37
+ var err = $('parsererror', xmlDoc);
38
+ if ( err.length == 1 ) {
39
+ throw('Error: ' + $(xmlDoc).text() );
40
+ }
41
+ } else {
42
+ throw('Unable to parse XML');
43
+ }
44
+ return xmlDoc;
45
+ } catch( e ) {
46
+ var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );
47
+ $(document).trigger('xmlParseError', [ msg ]);
48
+ return undefined;
49
+ }
50
+ }
51
+
52
+ // Trigger a jQuery event
53
+ function trigger(s, type, args) {
54
+ (s.context ? $(s.context) : $.event).trigger(type, args);
55
+ }
56
+
57
+ // Check if the data field on the mock handler and the request match. This
58
+ // can be used to restrict a mock handler to being used only when a certain
59
+ // set of data is passed to it.
60
+ function isMockDataEqual( mock, live ) {
61
+ var identical = true;
62
+ // Test for situations where the data is a querystring (not an object)
63
+ if (typeof live === 'string') {
64
+ // Querystring may be a regex
65
+ return $.isFunction( mock.test ) ? mock.test(live) : mock == live;
66
+ }
67
+ $.each(mock, function(k) {
68
+ if ( live[k] === undefined ) {
69
+ identical = false;
70
+ return identical;
71
+ } else {
72
+ if ( typeof live[k] == 'object' ) {
73
+ identical = identical && isMockDataEqual(mock[k], live[k]);
74
+ } else {
75
+ if ( $.isFunction( mock[k].test ) ) {
76
+ identical = identical && mock[k].test(live[k]);
77
+ } else {
78
+ identical = identical && ( mock[k] == live[k] );
79
+ }
80
+ }
81
+ }
82
+ });
83
+
84
+ return identical;
85
+ }
86
+
87
+ // Check the given handler should mock the given request
88
+ function getMockForRequest( handler, requestSettings ) {
89
+ // If the mock was registered with a function, let the function decide if we
90
+ // want to mock this request
91
+ if ( $.isFunction(handler) ) {
92
+ return handler( requestSettings );
93
+ }
94
+
95
+ // Inspect the URL of the request and check if the mock handler's url
96
+ // matches the url for this ajax request
97
+ if ( $.isFunction(handler.url.test) ) {
98
+ // The user provided a regex for the url, test it
99
+ if ( !handler.url.test( requestSettings.url ) ) {
100
+ return null;
101
+ }
102
+ } else {
103
+ // Look for a simple wildcard '*' or a direct URL match
104
+ var star = handler.url.indexOf('*');
105
+ if (handler.url !== requestSettings.url && star === -1 ||
106
+ !new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace(/\*/g, '.+')).test(requestSettings.url)) {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ // Inspect the data submitted in the request (either POST body or GET query string)
112
+ if ( handler.data && requestSettings.data ) {
113
+ if ( !isMockDataEqual(handler.data, requestSettings.data) ) {
114
+ // They're not identical, do not mock this request
115
+ return null;
116
+ }
117
+ }
118
+ // Inspect the request type
119
+ if ( handler && handler.type &&
120
+ handler.type.toLowerCase() != requestSettings.type.toLowerCase() ) {
121
+ // The request type doesn't match (GET vs. POST)
122
+ return null;
123
+ }
124
+
125
+ return handler;
126
+ }
127
+
128
+ // Process the xhr objects send operation
129
+ function _xhrSend(mockHandler, requestSettings, origSettings) {
130
+
131
+ // This is a substitute for < 1.4 which lacks $.proxy
132
+ var process = (function(that) {
133
+ return function() {
134
+ return (function() {
135
+ var onReady;
136
+
137
+ // The request has returned
138
+ this.status = mockHandler.status;
139
+ this.statusText = mockHandler.statusText;
140
+ this.readyState = 4;
141
+
142
+ // We have an executable function, call it to give
143
+ // the mock handler a chance to update it's data
144
+ if ( $.isFunction(mockHandler.response) ) {
145
+ mockHandler.response(origSettings);
146
+ }
147
+ // Copy over our mock to our xhr object before passing control back to
148
+ // jQuery's onreadystatechange callback
149
+ if ( requestSettings.dataType == 'json' && ( typeof mockHandler.responseText == 'object' ) ) {
150
+ this.responseText = JSON.stringify(mockHandler.responseText);
151
+ } else if ( requestSettings.dataType == 'xml' ) {
152
+ if ( typeof mockHandler.responseXML == 'string' ) {
153
+ this.responseXML = parseXML(mockHandler.responseXML);
154
+ //in jQuery 1.9.1+, responseXML is processed differently and relies on responseText
155
+ this.responseText = mockHandler.responseXML;
156
+ } else {
157
+ this.responseXML = mockHandler.responseXML;
158
+ }
159
+ } else {
160
+ this.responseText = mockHandler.responseText;
161
+ }
162
+ if( typeof mockHandler.status == 'number' || typeof mockHandler.status == 'string' ) {
163
+ this.status = mockHandler.status;
164
+ }
165
+ if( typeof mockHandler.statusText === "string") {
166
+ this.statusText = mockHandler.statusText;
167
+ }
168
+ // jQuery 2.0 renamed onreadystatechange to onload
169
+ onReady = this.onreadystatechange || this.onload;
170
+
171
+ // jQuery < 1.4 doesn't have onreadystate change for xhr
172
+ if ( $.isFunction( onReady ) ) {
173
+ if( mockHandler.isTimeout) {
174
+ this.status = -1;
175
+ }
176
+ onReady.call( this, mockHandler.isTimeout ? 'timeout' : undefined );
177
+ } else if ( mockHandler.isTimeout ) {
178
+ // Fix for 1.3.2 timeout to keep success from firing.
179
+ this.status = -1;
180
+ }
181
+ }).apply(that);
182
+ };
183
+ })(this);
184
+
185
+ if ( mockHandler.proxy ) {
186
+ // We're proxying this request and loading in an external file instead
187
+ _ajax({
188
+ global: false,
189
+ url: mockHandler.proxy,
190
+ type: mockHandler.proxyType,
191
+ data: mockHandler.data,
192
+ dataType: requestSettings.dataType === "script" ? "text/plain" : requestSettings.dataType,
193
+ complete: function(xhr) {
194
+ mockHandler.responseXML = xhr.responseXML;
195
+ mockHandler.responseText = xhr.responseText;
196
+ mockHandler.status = xhr.status;
197
+ mockHandler.statusText = xhr.statusText;
198
+ this.responseTimer = setTimeout(process, mockHandler.responseTime || 0);
199
+ }
200
+ });
201
+ } else {
202
+ // type == 'POST' || 'GET' || 'DELETE'
203
+ if ( requestSettings.async === false ) {
204
+ // TODO: Blocking delay
205
+ process();
206
+ } else {
207
+ this.responseTimer = setTimeout(process, mockHandler.responseTime || 50);
208
+ }
209
+ }
210
+ }
211
+
212
+ // Construct a mocked XHR Object
213
+ function xhr(mockHandler, requestSettings, origSettings, origHandler) {
214
+ // Extend with our default mockjax settings
215
+ mockHandler = $.extend(true, {}, $.mockjaxSettings, mockHandler);
216
+
217
+ if (typeof mockHandler.headers === 'undefined') {
218
+ mockHandler.headers = {};
219
+ }
220
+ if ( mockHandler.contentType ) {
221
+ mockHandler.headers['content-type'] = mockHandler.contentType;
222
+ }
223
+
224
+ return {
225
+ status: mockHandler.status,
226
+ statusText: mockHandler.statusText,
227
+ readyState: 1,
228
+ open: function() { },
229
+ send: function() {
230
+ origHandler.fired = true;
231
+ _xhrSend.call(this, mockHandler, requestSettings, origSettings);
232
+ },
233
+ abort: function() {
234
+ clearTimeout(this.responseTimer);
235
+ },
236
+ setRequestHeader: function(header, value) {
237
+ mockHandler.headers[header] = value;
238
+ },
239
+ getResponseHeader: function(header) {
240
+ // 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
241
+ if ( mockHandler.headers && mockHandler.headers[header] ) {
242
+ // Return arbitrary headers
243
+ return mockHandler.headers[header];
244
+ } else if ( header.toLowerCase() == 'last-modified' ) {
245
+ return mockHandler.lastModified || (new Date()).toString();
246
+ } else if ( header.toLowerCase() == 'etag' ) {
247
+ return mockHandler.etag || '';
248
+ } else if ( header.toLowerCase() == 'content-type' ) {
249
+ return mockHandler.contentType || 'text/plain';
250
+ }
251
+ },
252
+ getAllResponseHeaders: function() {
253
+ var headers = '';
254
+ $.each(mockHandler.headers, function(k, v) {
255
+ headers += k + ': ' + v + "\n";
256
+ });
257
+ return headers;
258
+ }
259
+ };
260
+ }
261
+
262
+ // Process a JSONP mock request.
263
+ function processJsonpMock( requestSettings, mockHandler, origSettings ) {
264
+ // Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
265
+ // because there isn't an easy hook for the cross domain script tag of jsonp
266
+
267
+ processJsonpUrl( requestSettings );
268
+
269
+ requestSettings.dataType = "json";
270
+ if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {
271
+ createJsonpCallback(requestSettings, mockHandler, origSettings);
272
+
273
+ // We need to make sure
274
+ // that a JSONP style response is executed properly
275
+
276
+ var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
277
+ parts = rurl.exec( requestSettings.url ),
278
+ remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
279
+
280
+ requestSettings.dataType = "script";
281
+ if(requestSettings.type.toUpperCase() === "GET" && remote ) {
282
+ var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings );
283
+
284
+ // Check if we are supposed to return a Deferred back to the mock call, or just
285
+ // signal success
286
+ if(newMockReturn) {
287
+ return newMockReturn;
288
+ } else {
289
+ return true;
290
+ }
291
+ }
292
+ }
293
+ return null;
294
+ }
295
+
296
+ // Append the required callback parameter to the end of the request URL, for a JSONP request
297
+ function processJsonpUrl( requestSettings ) {
298
+ if ( requestSettings.type.toUpperCase() === "GET" ) {
299
+ if ( !CALLBACK_REGEX.test( requestSettings.url ) ) {
300
+ requestSettings.url += (/\?/.test( requestSettings.url ) ? "&" : "?") +
301
+ (requestSettings.jsonp || "callback") + "=?";
302
+ }
303
+ } else if ( !requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data) ) {
304
+ requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?";
305
+ }
306
+ }
307
+
308
+ // Process a JSONP request by evaluating the mocked response text
309
+ function processJsonpRequest( requestSettings, mockHandler, origSettings ) {
310
+ // Synthesize the mock request for adding a script tag
311
+ var callbackContext = origSettings && origSettings.context || requestSettings,
312
+ newMock = null;
313
+
314
+
315
+ // If the response handler on the moock is a function, call it
316
+ if ( mockHandler.response && $.isFunction(mockHandler.response) ) {
317
+ mockHandler.response(origSettings);
318
+ } else {
319
+
320
+ // Evaluate the responseText javascript in a global context
321
+ if( typeof mockHandler.responseText === 'object' ) {
322
+ $.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')');
323
+ } else {
324
+ $.globalEval( '(' + mockHandler.responseText + ')');
325
+ }
326
+ }
327
+
328
+ // Successful response
329
+ jsonpSuccess( requestSettings, callbackContext, mockHandler );
330
+ jsonpComplete( requestSettings, callbackContext, mockHandler );
331
+
332
+ // If we are running under jQuery 1.5+, return a deferred object
333
+ if($.Deferred){
334
+ newMock = new $.Deferred();
335
+ if(typeof mockHandler.responseText == "object"){
336
+ newMock.resolveWith( callbackContext, [mockHandler.responseText] );
337
+ }
338
+ else{
339
+ newMock.resolveWith( callbackContext, [$.parseJSON( mockHandler.responseText )] );
340
+ }
341
+ }
342
+ return newMock;
343
+ }
344
+
345
+
346
+ // Create the required JSONP callback function for the request
347
+ function createJsonpCallback( requestSettings, mockHandler, origSettings ) {
348
+ var callbackContext = origSettings && origSettings.context || requestSettings;
349
+ var jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++);
350
+
351
+ // Replace the =? sequence both in the query string and the data
352
+ if ( requestSettings.data ) {
353
+ requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1");
354
+ }
355
+
356
+ requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1");
357
+
358
+
359
+ // Handle JSONP-style loading
360
+ window[ jsonp ] = window[ jsonp ] || function( tmp ) {
361
+ data = tmp;
362
+ jsonpSuccess( requestSettings, callbackContext, mockHandler );
363
+ jsonpComplete( requestSettings, callbackContext, mockHandler );
364
+ // Garbage collect
365
+ window[ jsonp ] = undefined;
366
+
367
+ try {
368
+ delete window[ jsonp ];
369
+ } catch(e) {}
370
+
371
+ if ( head ) {
372
+ head.removeChild( script );
373
+ }
374
+ };
375
+ }
376
+
377
+ // The JSONP request was successful
378
+ function jsonpSuccess(requestSettings, callbackContext, mockHandler) {
379
+ // If a local callback was specified, fire it and pass it the data
380
+ if ( requestSettings.success ) {
381
+ requestSettings.success.call( callbackContext, mockHandler.responseText || "", status, {} );
382
+ }
383
+
384
+ // Fire the global callback
385
+ if ( requestSettings.global ) {
386
+ trigger(requestSettings, "ajaxSuccess", [{}, requestSettings] );
387
+ }
388
+ }
389
+
390
+ // The JSONP request was completed
391
+ function jsonpComplete(requestSettings, callbackContext) {
392
+ // Process result
393
+ if ( requestSettings.complete ) {
394
+ requestSettings.complete.call( callbackContext, {} , status );
395
+ }
396
+
397
+ // The request was completed
398
+ if ( requestSettings.global ) {
399
+ trigger( "ajaxComplete", [{}, requestSettings] );
400
+ }
401
+
402
+ // Handle the global AJAX counter
403
+ if ( requestSettings.global && ! --$.active ) {
404
+ $.event.trigger( "ajaxStop" );
405
+ }
406
+ }
407
+
408
+
409
+ // The core $.ajax replacement.
410
+ function handleAjax( url, origSettings ) {
411
+ var mockRequest, requestSettings, mockHandler;
412
+
413
+ // If url is an object, simulate pre-1.5 signature
414
+ if ( typeof url === "object" ) {
415
+ origSettings = url;
416
+ url = undefined;
417
+ } else {
418
+ // work around to support 1.5 signature
419
+ origSettings.url = url;
420
+ }
421
+
422
+ // Extend the original settings for the request
423
+ requestSettings = $.extend(true, {}, $.ajaxSettings, origSettings);
424
+
425
+ // Iterate over our mock handlers (in registration order) until we find
426
+ // one that is willing to intercept the request
427
+ for(var k = 0; k < mockHandlers.length; k++) {
428
+ if ( !mockHandlers[k] ) {
429
+ continue;
430
+ }
431
+
432
+ mockHandler = getMockForRequest( mockHandlers[k], requestSettings );
433
+ if(!mockHandler) {
434
+ // No valid mock found for this request
435
+ continue;
436
+ }
437
+
438
+ mockedAjaxCalls.push(requestSettings);
439
+
440
+ // If logging is enabled, log the mock to the console
441
+ $.mockjaxSettings.log( mockHandler, requestSettings );
442
+
443
+
444
+ if ( requestSettings.dataType === "jsonp" ) {
445
+ if ((mockRequest = processJsonpMock( requestSettings, mockHandler, origSettings ))) {
446
+ // This mock will handle the JSONP request
447
+ return mockRequest;
448
+ }
449
+ }
450
+
451
+
452
+ // Removed to fix #54 - keep the mocking data object intact
453
+ //mockHandler.data = requestSettings.data;
454
+
455
+ mockHandler.cache = requestSettings.cache;
456
+ mockHandler.timeout = requestSettings.timeout;
457
+ mockHandler.global = requestSettings.global;
458
+
459
+ copyUrlParameters(mockHandler, origSettings);
460
+
461
+ (function(mockHandler, requestSettings, origSettings, origHandler) {
462
+ mockRequest = _ajax.call($, $.extend(true, {}, origSettings, {
463
+ // Mock the XHR object
464
+ xhr: function() { return xhr( mockHandler, requestSettings, origSettings, origHandler ); }
465
+ }));
466
+ })(mockHandler, requestSettings, origSettings, mockHandlers[k]);
467
+
468
+ return mockRequest;
469
+ }
470
+
471
+ // We don't have a mock request, trigger a normal request
472
+ return _ajax.apply($, [origSettings]);
473
+ }
474
+
475
+ /**
476
+ * Copies URL parameter values if they were captured by a regular expression
477
+ * @param {Object} mockHandler
478
+ * @param {Object} origSettings
479
+ */
480
+ function copyUrlParameters(mockHandler, origSettings) {
481
+ //parameters aren't captured if the URL isn't a RegExp
482
+ if (!(mockHandler.url instanceof RegExp)) {
483
+ return;
484
+ }
485
+ //if no URL params were defined on the handler, don't attempt a capture
486
+ if (!mockHandler.hasOwnProperty('urlParams')) {
487
+ return;
488
+ }
489
+ var captures = mockHandler.url.exec(origSettings.url);
490
+ //the whole RegExp match is always the first value in the capture results
491
+ if (captures.length === 1) {
492
+ return;
493
+ }
494
+ captures.shift();
495
+ //use handler params as keys and capture resuts as values
496
+ var i = 0,
497
+ capturesLength = captures.length,
498
+ paramsLength = mockHandler.urlParams.length,
499
+ //in case the number of params specified is less than actual captures
500
+ maxIterations = Math.min(capturesLength, paramsLength),
501
+ paramValues = {};
502
+ for (i; i < maxIterations; i++) {
503
+ var key = mockHandler.urlParams[i];
504
+ paramValues[key] = captures[i];
505
+ }
506
+ origSettings.urlParams = paramValues;
507
+ }
508
+
509
+
510
+ // Public
511
+
512
+ $.extend({
513
+ ajax: handleAjax
514
+ });
515
+
516
+ $.mockjaxSettings = {
517
+ //url: null,
518
+ //type: 'GET',
519
+ log: function( mockHandler, requestSettings ) {
520
+ if ( mockHandler.logging === false ||
521
+ ( typeof mockHandler.logging === 'undefined' && $.mockjaxSettings.logging === false ) ) {
522
+ return;
523
+ }
524
+ if ( window.console && console.log ) {
525
+ var message = 'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url;
526
+ var request = $.extend({}, requestSettings);
527
+
528
+ if (typeof console.log === 'function') {
529
+ console.log(message, request);
530
+ } else {
531
+ try {
532
+ console.log( message + ' ' + JSON.stringify(request) );
533
+ } catch (e) {
534
+ console.log(message);
535
+ }
536
+ }
537
+ }
538
+ },
539
+ logging: true,
540
+ status: 200,
541
+ statusText: "OK",
542
+ responseTime: 500,
543
+ isTimeout: false,
544
+ contentType: 'text/plain',
545
+ response: '',
546
+ responseText: '',
547
+ responseXML: '',
548
+ proxy: '',
549
+ proxyType: 'GET',
550
+
551
+ lastModified: null,
552
+ etag: '',
553
+ headers: {
554
+ etag: 'IJF@H#@923uf8023hFO@I#H#',
555
+ 'content-type' : 'text/plain'
556
+ }
557
+ };
558
+
559
+ $.mockjax = function(settings) {
560
+ var i = mockHandlers.length;
561
+ mockHandlers[i] = settings;
562
+ return i;
563
+ };
564
+ $.mockjaxClear = function(i) {
565
+ if ( arguments.length == 1 ) {
566
+ mockHandlers[i] = null;
567
+ } else {
568
+ mockHandlers = [];
569
+ }
570
+ mockedAjaxCalls = [];
571
+ };
572
+ $.mockjax.handler = function(i) {
573
+ if ( arguments.length == 1 ) {
574
+ return mockHandlers[i];
575
+ }
576
+ };
577
+ $.mockjax.mockedAjaxCalls = function() {
578
+ return mockedAjaxCalls;
579
+ };
580
+ })(jQuery);