├── .gitignore ├── .jshintrc ├── Gruntfile.coffee ├── README.md ├── bower.json ├── jquery.narrows.js ├── jquery.narrows.min.js ├── lib ├── jasmine-1.3.1 │ ├── MIT.LICENSE │ ├── boot.js │ ├── jasmine-html.js │ ├── jasmine.css │ └── jasmine.js ├── jasmine-2.0.0 │ ├── boot.js │ ├── jasmine-html.js │ ├── jasmine.css │ └── jasmine.js └── run-jasmine.js ├── package.json ├── sample-jasmine-2.0.0.html ├── sample.html └── spec └── narrowsSpec.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *.swp 3 | .#* 4 | /memo.narrows.txt 5 | /node_modules 6 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "loopfunc": true 3 | } 4 | -------------------------------------------------------------------------------- /Gruntfile.coffee: -------------------------------------------------------------------------------- 1 | module.exports = (grunt) -> 2 | pkg = grunt.file.readJSON 'package.json' 3 | 4 | grunt.initConfig 5 | jshint: 6 | files: ['jquery.narrows.js'] 7 | options: 8 | jshintrc: ".jshintrc" 9 | jasmine: 10 | src: 'jquery.narrows.js' 11 | options: 12 | template: 'sample.html' 13 | uglify: 14 | options: 15 | preserveComments: 'some' 16 | dest: 17 | files: 18 | 'jquery.narrows.min.js': 'jquery.narrows.js' 19 | watch: 20 | files: ['jquery.narrows.js'], 21 | tasks: ['uglify', 'jshint'] 22 | 23 | for taskName of pkg.devDependencies 24 | if taskName.substring(0, 6) is 'grunt-' 25 | grunt.loadNpmTasks taskName 26 | 27 | grunt.registerTask 'default', ['jshint', 'jasmine', 'uglify', 'watch'] 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jQuery Select Narrowing Plugin
(select 絞り込みプラグイン) 2 | 3 | * Version: 0.3.1 4 | * Author: Shimon Yamada 5 | 6 | ## これはなに? 7 | 8 | いわゆる hierselect プラグインです。 9 | 複数の select 間に階層関係を持たせて、ある select での選択結果により別の select の選択肢を絞り込ませる (narrows) ことができます。 10 | 11 | ## 例 12 | 13 | ぐだぐだ説明するよりまずサンプルを触って貰った方が分かりやすいかと思います。。。 14 | → [sample.html](http://monmonmon.github.io/jquery.narrows/sample.html) 15 | 16 | ## ウリ 17 | 18 | * サーバサイドの実装なしに、JS と HTML だけで動作します。サーバサイドが PHP だろうが Ruby だろうが Java だろうが関係なく動きます。素敵。 19 | * 単純な「親→子」だけでなく、「親→子→孫→ひ孫…」と、何階層でも連鎖させられます。 20 | 国→エリア→都市、とか。 21 | * 「親→子1&子2」のように、1つの親 select に複数の子 select を持たせられます。 22 | * 「親1&親2→子」のように、複数の親 select の選択結果により子 select の選択肢を絞り込んだりできます。 23 | 例えば select1 で色を、select2 で形をそれぞれ選択して、select3 の選択肢を絞り込んだりとか。 24 | * これらを組み合わせて、いくらでも複雑な階層関係を表現できます。できるはず。あまり複雑な階層関係で実験したことないですけど。。。 25 | 26 | ## 制約 27 | 28 | * 使用する select(親selectも子selectも)は全て id 属性が必須です。 29 | * 子 select の option には独自のデータ属性 (data-xx="yy" のような属性) を設定する必要があります。 30 | * select の option を動的に追加・削除しています。このような動作と競合するようなライブラリやスクリプトとは共存できません。 31 | * optgroup のある select には未対応です。 32 | 33 | ## 使い方 34 | 35 | ### ☆ 使い方その1 ☆ 36 | 37 | シンプルな例。 38 | 39 | まず HTML で select を記述します。この例では、食品カテゴリと食品の2つの select を作ります。 40 | 階層関係は、この select, option の HTML 属性で定義します。 41 | 42 | * 親子とも、select 要素の id 属性は必須です。ここでは親 select を **"category"**, 子 select を **"food"** とします。 43 | * 子 select の option のデータ属性(**"data-xx"** てやつ)で、どの親 select のどの値で絞り込むか、を定義します。 44 | * データ属性名は **"data-<親 select の id 名>"** です。親 select の id は category なので、この場合のデータ属性名は **data-category** です。 45 | * このデータ属性は、子 select の value="" 以外の全ての option で必須です。 46 | * このデータ属性の値で、親 select のどの値の時に有効となるかを定義します。 47 | data-category="meat" なら、親 select で value="meat" が選択された時に有効になります。 48 | 49 | 50 | 51 | 52 | 58 | 59 | 71 | 72 | jQuery プラグインで階層関係を登録します。以下のように呼ぶだけです。 73 | 74 | 79 | 80 | 81 | 82 | ### ☆ 使い方その2 ☆ 83 | 84 | 3階層の例です。大陸→国→都市。 85 | 86 | 87 | 92 | 93 | 102 | 103 | 115 | 116 | プラグインは2回呼びます。 117 | 118 | 124 | 125 | 126 | 127 | ### ☆ 使い方その3 ☆ 128 | 129 | 1つの親 select が複数の子 select を同時に絞り込む例。 130 | 131 | 国籍を選択すると、その国籍の料理、酒がそれぞれ選択できるようになる。 132 | 133 | 134 | 140 | 141 | 153 | 154 | 168 | 169 | 170 | 171 | 179 | 180 | 181 | 182 | ### ☆ 使い方その4 ☆ 183 | 184 | 複数の親 select の選択結果により子 select を絞り込む例。 185 | 186 | 国籍とカテゴリを選択すると、選んだ国、カテゴリに対応する食べ物が選択できるようになる。 187 | 親が複数の場合は、子 select の option に与えるデータ属性 **data-xx** が同じ数だけ必要になります。 188 | この例では親 select は id-"country", id="category" なので、子 select の option には data-country, data-category の2つのデータ属性を与えます。 189 | 190 | 191 | 197 | 198 | 204 | 205 | 220 | 221 | 222 | 223 | 228 | 229 | ## オプション 230 | 231 | 第2引数にオプションを指定できます。 232 | 233 | $("#parent").narrows("#child", { 234 | disable_if_parent_is_null: true, 235 | null_value: '', 236 | allow_multiple_parent_values: false, 237 | multiple_parent_values_separator: ' *, *', 238 | }); 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 255 | 256 | 257 | 258 | 259 | 260 | 264 | 265 | 266 | 267 | 268 | 269 | 272 | 273 | 274 | 275 | 276 | 277 | 280 | 281 |
オプションデフォルト値説明
disable_if_parent_is_nullbooleantrue 252 | true ... 親selectで value="" を選択した場合、子selectを選択不可とする。
253 | false ... 親selectで value="" を選択した場合、子selectで全てのoptionを選択可とする。 254 |
null_valuestring"" 261 | option の value 属性が空値だと判断する値。
262 | null_value を 0 とすると value="0" の時に空値と判断する。 263 |
allow_multiple_parent_valuesbooleanfalse 270 | 子selectのoptionの data-xx 属性に複数の値を指定することで、親selectの複数のoptionにマッチ可能とする。 271 |
multiple_parent_values_separatorstring" *, *" 278 | allow_multiple_parent_values オプションが true の際、data-xx 属性の複数の値を分割するセパレータ(正規表現)。 279 |
282 | 283 | ## 対応ブラウザ 284 | 285 | MacOSX 286 | 287 | * Google Chrome 29+ 288 | * Firefox 20+ 289 | * Opera 12+ 290 | * Safari 6+ 291 | 292 | Windows 293 | 294 | * Internet Explorer 6 295 | * Firefox 10くらい 296 | 297 | で動作確認。 298 | 299 | ## License 300 | 301 | Licensed under the [MIT](http://www.opensource.org/licenses/MIT) license. 302 | 303 | Copyright 2013 Shimon Yamada 304 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jquery.narrows.js", 3 | "version": "0.3.1", 4 | "main": "jquery.narrows.js", 5 | "description": "jQuery Hierselect Plugin", 6 | "license": "MIT", 7 | "ignore": [ 8 | "**/.*", 9 | "**/*.html", 10 | "Gruntfile.coffee", 11 | "node_modules", 12 | "README.md", 13 | "package.json", 14 | "lib", 15 | "spec" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /jquery.narrows.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * jQuery narrowing plugin 3 | * Version 0.0.2 4 | * @requires jQuery v1.7.0 or later 5 | * 6 | * Copyright 2013 Simon Yamada 山田史門 7 | * Dual licensed under the MIT and GPL licenses: 8 | * http://www.opensource.org/licenses/mit-license.php 9 | * http://www.gnu.org/licenses/gpl.html 10 | * 11 | * Date: 2013-09-11 12 | */ 13 | (function ($) { 14 | var methods = { 15 | __relations: {}, // 親子関係を保持する配列 16 | __options: {}, // 子selectごとにoptionを全て保持 17 | __ukeys: {}, // selectに与えるユニークキーのリストを保持 18 | __ukey_name: 'jquery-narrows-unique-key', // select要素に付与するユニークキーの属性名 19 | __default_params: { 20 | disable_if_parent_is_null: true, 21 | null_value: '', 22 | allow_multiple_parent_values: false, 23 | multiple_parent_values_separator: ' *, *', 24 | }, 25 | // 初期化 26 | init: function (selector, params) { 27 | var $parents = this; 28 | var $children = $(selector); 29 | // 引数チェック 30 | methods.validate_selects($parents, $children); 31 | // 設定のデフォルト値をオーバーライド 32 | var __params = {}; 33 | for (var key in methods.__default_params) { 34 | __params[key] = params && params[key] !== void 0 ? params[key] : methods.__default_params[key]; 35 | } 36 | if (__params.allow_multiple_parent_values) { 37 | __params.regexp_separator = new RegExp(__params.multiple_parent_values_separator); 38 | } 39 | params = __params; 40 | // この親子関係を登録 41 | methods.register_new_relations($parents, $children, params); 42 | // 子selectはとりあえず全てdisable(直後に適宜enable) 43 | if (params.disable_if_parent_is_null) { 44 | $children.attr('disabled', 'disabled'); 45 | } 46 | // 親selectのイベントハンドラを設定 47 | $parents.on('change', methods.onchange_handler); 48 | // 絞り込みを初期化 49 | var relations = methods.get_relations_of($parents); 50 | for (var relation_i = 0, len = relations.length; relation_i < len; relation_i++) { 51 | var relation = relations[relation_i]; 52 | if (relation.initialized) { 53 | // 初期化は1回だけ 54 | continue; 55 | } 56 | relation.initialized = true; 57 | methods.manage_this_relation(relation); 58 | } 59 | return $parents; 60 | }, 61 | // 親子それぞれの select, option が正しく記述されているかをチェック 62 | validate_selects: function ($parents, $children) { 63 | // 親子select共通のチェック 64 | var arr = [$parents, $children]; 65 | for (var arr_i = 0, len = arr.length; arr_i < len; arr_i++) { 66 | var $selects = arr[arr_i]; 67 | if (0 === $selects.size()) { 68 | $.error('selector '+$selects.selector+': element not found'); 69 | } 70 | $selects.each(function () { 71 | if ('SELECT' != $(this).prop('tagName')) { 72 | $.error('selector '+$selects.selector+': includes non-select element(s)'); 73 | } 74 | if (!$(this).attr('id')) { 75 | $.error('id is required for all select elements'); 76 | } 77 | }); 78 | } 79 | // 親子関係を data-x 属性で正しく記述しているかチェック 80 | var parent_ids = $parents.map(function () { return $(this).attr('id'); }); 81 | $children.each(function () { 82 | for (var p_i = 0, len = parent_ids.length; p_i < len; p_i++) { 83 | var attr = 'data-' + parent_ids[p_i]; 84 | var $select = $(this); 85 | $select.find('option').each(function () { 86 | // value="" の option 以外は data- 属性必須 87 | var $option = $(this); 88 | if ($option.val() && !$option.attr(attr)) { 89 | var id = $select.attr('id'); 90 | $.error('options of select "#'+id+'" require "'+attr+'" attribute'); 91 | } 92 | }); 93 | } 94 | }); 95 | }, 96 | // 親子関係を新規登録 97 | register_new_relations: function ($parents, $children, params) { 98 | // 親子それぞれの select にランダムなユニークキーを割り当てる 99 | var parent_keys = []; 100 | $parents.each(function () { 101 | var parent_key = methods.unique_key($(this)); 102 | parent_keys.push(parent_key); 103 | }); 104 | var child_keys = []; 105 | $children.each(function () { 106 | var child_key = methods.unique_key($(this)); 107 | child_keys.push(child_key); 108 | // 子selectのoptionを配列で全部持つ 109 | methods.__options[child_key] = $(this).find('option').get(); 110 | }); 111 | // 親selectのユニークキーをキーとして、親子関係を __relations に保持する 112 | for (var p_i = 0, len = parent_keys.length; p_i < len; p_i++) { 113 | var parent_key = parent_keys[p_i]; 114 | if (!methods.__relations[parent_key]) 115 | methods.__relations[parent_key] = []; 116 | methods.__relations[parent_key].push({ 117 | $parents:$parents, 118 | $children:$children, 119 | params:params, 120 | initialized:false 121 | }); 122 | } 123 | }, 124 | // ユニークなキーを生成して $element に属性として与える 125 | unique_key: function ($element) { 126 | // 割り当て済みのunique keyがあればそれを返す 127 | var ukey = $element.data(methods.__ukey_name); 128 | if (ukey) { 129 | return ukey; 130 | } 131 | // ユニークなキーを生成 132 | do { 133 | ukey = (Math.random() * 10000000 | 0).toString(16); 134 | } while (methods.__ukeys[ukey] !== void 0); 135 | $element.data(methods.__ukey_name, ukey); 136 | // キャッシュ 137 | methods.__ukeys[ukey] = 1; 138 | return ukey; 139 | }, 140 | // 親selectのchangeイベントハンドラ 141 | onchange_handler: function (e) { 142 | var relations = methods.get_relations_of($(this)); 143 | for (var relation_i = 0, len = relations.length; relation_i < len; relation_i++) { 144 | var relation = relations[relation_i]; 145 | methods.manage_this_relation(relation); 146 | } 147 | }, 148 | // 親selectで選択された値に基づいて子selectを絞り込む 149 | manage_this_relation: function (relation) { 150 | // 全ての親selectで選択したvalueを調べる 151 | var parent_selected_values = {}; 152 | var all_parents_selected = true; 153 | relation.$parents.each(function () { 154 | var value = $(this).val(); 155 | if (value == relation.params.null_value) { 156 | all_parents_selected = false; 157 | return false; 158 | } 159 | parent_selected_values[$(this).attr('id')] = value; 160 | }); 161 | if (all_parents_selected) { 162 | // この親子関係の全ての親selectで value="" 以外の値が選択された。 163 | // 対応するoptionを子selectに追加 164 | relation.$children.each(function () { 165 | methods.enable_relevant_options($(this), relation, parent_selected_values); 166 | }); 167 | } else { 168 | // この親子関係の親selectのどれかで value="" が選択された。 169 | if (relation.params.disable_if_parent_is_null) { 170 | // 子selectのoptionを全て削除してdisable 171 | relation.$children.each(function () { 172 | methods.disable_all_options($(this), relation); 173 | }); 174 | } else { 175 | // 子selectのoptionを全部表示 176 | relation.$children.each(function () { 177 | methods.enable_all_options($(this), relation); 178 | }); 179 | } 180 | } 181 | // 子孫selectへイベントを伝播 182 | relation.$children.trigger('change'); 183 | }, 184 | // 親selectで選択された値に対応するoptionを有効にする 185 | enable_relevant_options: function ($select, relation, parent_selected_values) { 186 | var previously_selected_value = $select.val(); 187 | $select 188 | // disabled解除 189 | .removeAttr('disabled') 190 | // option要素をDOMから一旦べしっと削除 191 | .find('option[value!=""]').remove(); 192 | // 全てのoptionのうち、親selectの選択結果に適合するもののみ追加 193 | var all_options = methods.get_all_options_of($select); 194 | for (var option_i = 0, len = all_options.length; option_i < len; option_i++) { 195 | var $option = $(all_options[option_i]); 196 | if (!$option.val()) { 197 | continue; 198 | } 199 | // このoptionが全ての親selectの選択結果にマッチするか確認 200 | var relevant_option = true; 201 | for (var parent_id in parent_selected_values) { 202 | var parent_selected_value = parent_selected_values[parent_id]; 203 | var relevant_value = $option.data(parent_id); 204 | if (relation.params.allow_multiple_parent_values) { 205 | // セパレータ区切りで複数の親にマッチ 206 | var relevant_values = relevant_value.toString().split(relation.params.regexp_separator); 207 | var matched_any = false; 208 | for (var r_i = 0, r_len = relevant_values.length; r_i < r_len; r_i++) { 209 | if (relevant_values[r_i] == parent_selected_value) { 210 | matched_any = true; break; 211 | } 212 | } 213 | if (!matched_any) { 214 | relevant_option = false; break; 215 | } 216 | } else { 217 | // 単一の親にマッチ 218 | if (relevant_value != parent_selected_value) { 219 | relevant_option = false; break; 220 | } 221 | } 222 | } 223 | if (relevant_option) { 224 | // このoptionを子selectに追加 225 | // さっきまで選択されてたoptionであればselectedに 226 | if ($option.val() == previously_selected_value) { 227 | $option.prop('selected', true); 228 | } 229 | $select.append($option); 230 | } 231 | } 232 | }, 233 | // 全てのoptionを有効にする 234 | enable_all_options: function ($select, relation) { 235 | var previously_selected_child_value = $select.val(); 236 | $select 237 | // disabled解除 238 | .removeAttr('disabled') 239 | // option要素をDOMから一旦べしっと削除 240 | .find('option[value!=""]').remove(); 241 | // 全てのoptionを追加 242 | var all_options = methods.get_all_options_of($select); 243 | for (var option_i = 0, len = all_options.length; option_i < len; option_i++) { 244 | var $option = $(all_options[option_i]); 245 | // さっきまで選択されてたoptionであればselectedに 246 | if ($option.val() == previously_selected_child_value) { 247 | $option.prop('selected', true); 248 | } 249 | $select.append($option); 250 | } 251 | }, 252 | // 全てのoptionを無効にする 253 | disable_all_options: function ($select, relation) { 254 | $select 255 | .attr('disabled', 'disabled').val(relation.params.null_value) 256 | .find('option[value!=""]').remove(); 257 | }, 258 | // $select を親とする全ての親子関係を取得する 259 | get_relations_of: function ($select) { 260 | var ukey = $select.data(methods.__ukey_name); 261 | return methods.__relations[ukey]; 262 | }, 263 | // $select の全ての option 要素を返す 264 | get_all_options_of: function ($select) { 265 | var ukey = $select.data(methods.__ukey_name); 266 | return methods.__options[ukey]; 267 | } 268 | }; 269 | $.fn.narrows = function (method) { 270 | // Method calling logic 271 | if (methods[method]) { 272 | return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 273 | } else if (typeof method === 'object' || typeof method === 'string' || !method) { 274 | return methods.init.apply(this, arguments); 275 | } else { 276 | $.error('Method ' + method + ' does not exist on jQuery.narrows'); 277 | } 278 | }; 279 | })(jQuery); 280 | -------------------------------------------------------------------------------- /jquery.narrows.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * jQuery narrowing plugin 3 | * Version 0.0.2 4 | * @requires jQuery v1.7.0 or later 5 | * 6 | * Copyright 2013 Simon Yamada 山田史門 7 | * Dual licensed under the MIT and GPL licenses: 8 | * http://www.opensource.org/licenses/mit-license.php 9 | * http://www.gnu.org/licenses/gpl.html 10 | * 11 | * Date: 2013-09-11 12 | */ 13 | !function(a){var b={__relations:{},__options:{},__ukeys:{},__ukey_name:"jquery-narrows-unique-key",__default_params:{disable_if_parent_is_null:!0,null_value:"",allow_multiple_parent_values:!1,multiple_parent_values_separator:" *, *"},init:function(c,d){var e=this,f=a(c);b.validate_selects(e,f);var g={};for(var h in b.__default_params)g[h]=d&&void 0!==d[h]?d[h]:b.__default_params[h];g.allow_multiple_parent_values&&(g.regexp_separator=new RegExp(g.multiple_parent_values_separator)),d=g,b.register_new_relations(e,f,d),d.disable_if_parent_is_null&&f.attr("disabled","disabled"),e.on("change",b.onchange_handler);for(var i=b.get_relations_of(e),j=0,k=i.length;k>j;j++){var l=i[j];l.initialized||(l.initialized=!0,b.manage_this_relation(l))}return e},validate_selects:function(b,c){for(var d=[b,c],e=0,f=d.length;f>e;e++){var g=d[e];0===g.size()&&a.error("selector "+g.selector+": element not found"),g.each(function(){"SELECT"!=a(this).prop("tagName")&&a.error("selector "+g.selector+": includes non-select element(s)"),a(this).attr("id")||a.error("id is required for all select elements")})}var h=b.map(function(){return a(this).attr("id")});c.each(function(){for(var b=0,c=h.length;c>b;b++){var d="data-"+h[b],e=a(this);e.find("option").each(function(){var b=a(this);if(b.val()&&!b.attr(d)){var c=e.attr("id");a.error('options of select "#'+c+'" require "'+d+'" attribute')}})}})},register_new_relations:function(c,d,e){var f=[];c.each(function(){var c=b.unique_key(a(this));f.push(c)});var g=[];d.each(function(){var c=b.unique_key(a(this));g.push(c),b.__options[c]=a(this).find("option").get()});for(var h=0,i=f.length;i>h;h++){var j=f[h];b.__relations[j]||(b.__relations[j]=[]),b.__relations[j].push({$parents:c,$children:d,params:e,initialized:!1})}},unique_key:function(a){var c=a.data(b.__ukey_name);if(c)return c;do c=(1e7*Math.random()|0).toString(16);while(void 0!==b.__ukeys[c]);return a.data(b.__ukey_name,c),b.__ukeys[c]=1,c},onchange_handler:function(c){for(var d=b.get_relations_of(a(this)),e=0,f=d.length;f>e;e++){var g=d[e];b.manage_this_relation(g)}},manage_this_relation:function(c){var d={},e=!0;c.$parents.each(function(){var b=a(this).val();return b==c.params.null_value?(e=!1,!1):void(d[a(this).attr("id")]=b)}),e?c.$children.each(function(){b.enable_relevant_options(a(this),c,d)}):c.params.disable_if_parent_is_null?c.$children.each(function(){b.disable_all_options(a(this),c)}):c.$children.each(function(){b.enable_all_options(a(this),c)}),c.$children.trigger("change")},enable_relevant_options:function(c,d,e){var f=c.val();c.removeAttr("disabled").find('option[value!=""]').remove();for(var g=b.get_all_options_of(c),h=0,i=g.length;i>h;h++){var j=a(g[h]);if(j.val()){var k=!0;for(var l in e){var m=e[l],n=j.data(l);if(d.params.allow_multiple_parent_values){for(var o=n.toString().split(d.params.regexp_separator),p=!1,q=0,r=o.length;r>q;q++)if(o[q]==m){p=!0;break}if(!p){k=!1;break}}else if(n!=m){k=!1;break}}k&&(j.val()==f&&j.prop("selected",!0),c.append(j))}}},enable_all_options:function(c,d){var e=c.val();c.removeAttr("disabled").find('option[value!=""]').remove();for(var f=b.get_all_options_of(c),g=0,h=f.length;h>g;g++){var i=a(f[g]);i.val()==e&&i.prop("selected",!0),c.append(i)}},disable_all_options:function(a,b){a.attr("disabled","disabled").val(b.params.null_value).find('option[value!=""]').remove()},get_relations_of:function(a){var c=a.data(b.__ukey_name);return b.__relations[c]},get_all_options_of:function(a){var c=a.data(b.__ukey_name);return b.__options[c]}};a.fn.narrows=function(c){return b[c]?b[c].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof c&&"string"!=typeof c&&c?void a.error("Method "+c+" does not exist on jQuery.narrows"):b.init.apply(this,arguments)}}(jQuery); -------------------------------------------------------------------------------- /lib/jasmine-1.3.1/MIT.LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2008-2011 Pivotal Labs 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /lib/jasmine-1.3.1/boot.js: -------------------------------------------------------------------------------- 1 | // boot the jasmine (copied from jasmine-standalone-1.3.1/SpecRunner.html) 2 | (function() { 3 | var jasmineEnv = jasmine.getEnv(); 4 | jasmineEnv.updateInterval = 1000; 5 | 6 | var htmlReporter = new jasmine.HtmlReporter(); 7 | 8 | jasmineEnv.addReporter(htmlReporter); 9 | 10 | jasmineEnv.specFilter = function(spec) { 11 | return htmlReporter.specFilter(spec); 12 | }; 13 | 14 | var currentWindowOnload = window.onload; 15 | 16 | window.onload = function() { 17 | if (currentWindowOnload) { 18 | currentWindowOnload(); 19 | } 20 | execJasmine(); 21 | }; 22 | 23 | function execJasmine() { 24 | jasmineEnv.execute(); 25 | } 26 | })(); 27 | -------------------------------------------------------------------------------- /lib/jasmine-1.3.1/jasmine-html.js: -------------------------------------------------------------------------------- 1 | jasmine.HtmlReporterHelpers = {}; 2 | 3 | jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) { 4 | var el = document.createElement(type); 5 | 6 | for (var i = 2; i < arguments.length; i++) { 7 | var child = arguments[i]; 8 | 9 | if (typeof child === 'string') { 10 | el.appendChild(document.createTextNode(child)); 11 | } else { 12 | if (child) { 13 | el.appendChild(child); 14 | } 15 | } 16 | } 17 | 18 | for (var attr in attrs) { 19 | if (attr == "className") { 20 | el[attr] = attrs[attr]; 21 | } else { 22 | el.setAttribute(attr, attrs[attr]); 23 | } 24 | } 25 | 26 | return el; 27 | }; 28 | 29 | jasmine.HtmlReporterHelpers.getSpecStatus = function(child) { 30 | var results = child.results(); 31 | var status = results.passed() ? 'passed' : 'failed'; 32 | if (results.skipped) { 33 | status = 'skipped'; 34 | } 35 | 36 | return status; 37 | }; 38 | 39 | jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) { 40 | var parentDiv = this.dom.summary; 41 | var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite'; 42 | var parent = child[parentSuite]; 43 | 44 | if (parent) { 45 | if (typeof this.views.suites[parent.id] == 'undefined') { 46 | this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views); 47 | } 48 | parentDiv = this.views.suites[parent.id].element; 49 | } 50 | 51 | parentDiv.appendChild(childElement); 52 | }; 53 | 54 | 55 | jasmine.HtmlReporterHelpers.addHelpers = function(ctor) { 56 | for(var fn in jasmine.HtmlReporterHelpers) { 57 | ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn]; 58 | } 59 | }; 60 | 61 | jasmine.HtmlReporter = function(_doc) { 62 | var self = this; 63 | var doc = _doc || window.document; 64 | 65 | var reporterView; 66 | 67 | var dom = {}; 68 | 69 | // Jasmine Reporter Public Interface 70 | self.logRunningSpecs = false; 71 | 72 | self.reportRunnerStarting = function(runner) { 73 | var specs = runner.specs() || []; 74 | 75 | if (specs.length == 0) { 76 | return; 77 | } 78 | 79 | createReporterDom(runner.env.versionString()); 80 | doc.body.appendChild(dom.reporter); 81 | setExceptionHandling(); 82 | 83 | reporterView = new jasmine.HtmlReporter.ReporterView(dom); 84 | reporterView.addSpecs(specs, self.specFilter); 85 | }; 86 | 87 | self.reportRunnerResults = function(runner) { 88 | reporterView && reporterView.complete(); 89 | }; 90 | 91 | self.reportSuiteResults = function(suite) { 92 | reporterView.suiteComplete(suite); 93 | }; 94 | 95 | self.reportSpecStarting = function(spec) { 96 | if (self.logRunningSpecs) { 97 | self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); 98 | } 99 | }; 100 | 101 | self.reportSpecResults = function(spec) { 102 | reporterView.specComplete(spec); 103 | }; 104 | 105 | self.log = function() { 106 | var console = jasmine.getGlobal().console; 107 | if (console && console.log) { 108 | if (console.log.apply) { 109 | console.log.apply(console, arguments); 110 | } else { 111 | console.log(arguments); // ie fix: console.log.apply doesn't exist on ie 112 | } 113 | } 114 | }; 115 | 116 | self.specFilter = function(spec) { 117 | if (!focusedSpecName()) { 118 | return true; 119 | } 120 | 121 | return spec.getFullName().indexOf(focusedSpecName()) === 0; 122 | }; 123 | 124 | return self; 125 | 126 | function focusedSpecName() { 127 | var specName; 128 | 129 | (function memoizeFocusedSpec() { 130 | if (specName) { 131 | return; 132 | } 133 | 134 | var paramMap = []; 135 | var params = jasmine.HtmlReporter.parameters(doc); 136 | 137 | for (var i = 0; i < params.length; i++) { 138 | var p = params[i].split('='); 139 | paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); 140 | } 141 | 142 | specName = paramMap.spec; 143 | })(); 144 | 145 | return specName; 146 | } 147 | 148 | function createReporterDom(version) { 149 | dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, 150 | dom.banner = self.createDom('div', { className: 'banner' }, 151 | self.createDom('span', { className: 'title' }, "Jasmine "), 152 | self.createDom('span', { className: 'version' }, version)), 153 | 154 | dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), 155 | dom.alert = self.createDom('div', {className: 'alert'}, 156 | self.createDom('span', { className: 'exceptions' }, 157 | self.createDom('label', { className: 'label', 'for': 'no_try_catch' }, 'No try/catch'), 158 | self.createDom('input', { id: 'no_try_catch', type: 'checkbox' }))), 159 | dom.results = self.createDom('div', {className: 'results'}, 160 | dom.summary = self.createDom('div', { className: 'summary' }), 161 | dom.details = self.createDom('div', { id: 'details' })) 162 | ); 163 | } 164 | 165 | function noTryCatch() { 166 | return window.location.search.match(/catch=false/); 167 | } 168 | 169 | function searchWithCatch() { 170 | var params = jasmine.HtmlReporter.parameters(window.document); 171 | var removed = false; 172 | var i = 0; 173 | 174 | while (!removed && i < params.length) { 175 | if (params[i].match(/catch=/)) { 176 | params.splice(i, 1); 177 | removed = true; 178 | } 179 | i++; 180 | } 181 | if (jasmine.CATCH_EXCEPTIONS) { 182 | params.push("catch=false"); 183 | } 184 | 185 | return params.join("&"); 186 | } 187 | 188 | function setExceptionHandling() { 189 | var chxCatch = document.getElementById('no_try_catch'); 190 | 191 | if (noTryCatch()) { 192 | chxCatch.setAttribute('checked', true); 193 | jasmine.CATCH_EXCEPTIONS = false; 194 | } 195 | chxCatch.onclick = function() { 196 | window.location.search = searchWithCatch(); 197 | }; 198 | } 199 | }; 200 | jasmine.HtmlReporter.parameters = function(doc) { 201 | var paramStr = doc.location.search.substring(1); 202 | var params = []; 203 | 204 | if (paramStr.length > 0) { 205 | params = paramStr.split('&'); 206 | } 207 | return params; 208 | } 209 | jasmine.HtmlReporter.sectionLink = function(sectionName) { 210 | var link = '?'; 211 | var params = []; 212 | 213 | if (sectionName) { 214 | params.push('spec=' + encodeURIComponent(sectionName)); 215 | } 216 | if (!jasmine.CATCH_EXCEPTIONS) { 217 | params.push("catch=false"); 218 | } 219 | if (params.length > 0) { 220 | link += params.join("&"); 221 | } 222 | 223 | return link; 224 | }; 225 | jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter); 226 | jasmine.HtmlReporter.ReporterView = function(dom) { 227 | this.startedAt = new Date(); 228 | this.runningSpecCount = 0; 229 | this.completeSpecCount = 0; 230 | this.passedCount = 0; 231 | this.failedCount = 0; 232 | this.skippedCount = 0; 233 | 234 | this.createResultsMenu = function() { 235 | this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'}, 236 | this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'), 237 | ' | ', 238 | this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing')); 239 | 240 | this.summaryMenuItem.onclick = function() { 241 | dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, ''); 242 | }; 243 | 244 | this.detailsMenuItem.onclick = function() { 245 | showDetails(); 246 | }; 247 | }; 248 | 249 | this.addSpecs = function(specs, specFilter) { 250 | this.totalSpecCount = specs.length; 251 | 252 | this.views = { 253 | specs: {}, 254 | suites: {} 255 | }; 256 | 257 | for (var i = 0; i < specs.length; i++) { 258 | var spec = specs[i]; 259 | this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views); 260 | if (specFilter(spec)) { 261 | this.runningSpecCount++; 262 | } 263 | } 264 | }; 265 | 266 | this.specComplete = function(spec) { 267 | this.completeSpecCount++; 268 | 269 | if (isUndefined(this.views.specs[spec.id])) { 270 | this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom); 271 | } 272 | 273 | var specView = this.views.specs[spec.id]; 274 | 275 | switch (specView.status()) { 276 | case 'passed': 277 | this.passedCount++; 278 | break; 279 | 280 | case 'failed': 281 | this.failedCount++; 282 | break; 283 | 284 | case 'skipped': 285 | this.skippedCount++; 286 | break; 287 | } 288 | 289 | specView.refresh(); 290 | this.refresh(); 291 | }; 292 | 293 | this.suiteComplete = function(suite) { 294 | var suiteView = this.views.suites[suite.id]; 295 | if (isUndefined(suiteView)) { 296 | return; 297 | } 298 | suiteView.refresh(); 299 | }; 300 | 301 | this.refresh = function() { 302 | 303 | if (isUndefined(this.resultsMenu)) { 304 | this.createResultsMenu(); 305 | } 306 | 307 | // currently running UI 308 | if (isUndefined(this.runningAlert)) { 309 | this.runningAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "runningAlert bar" }); 310 | dom.alert.appendChild(this.runningAlert); 311 | } 312 | this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount); 313 | 314 | // skipped specs UI 315 | if (isUndefined(this.skippedAlert)) { 316 | this.skippedAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "skippedAlert bar" }); 317 | } 318 | 319 | this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; 320 | 321 | if (this.skippedCount === 1 && isDefined(dom.alert)) { 322 | dom.alert.appendChild(this.skippedAlert); 323 | } 324 | 325 | // passing specs UI 326 | if (isUndefined(this.passedAlert)) { 327 | this.passedAlert = this.createDom('span', { href: jasmine.HtmlReporter.sectionLink(), className: "passingAlert bar" }); 328 | } 329 | this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount); 330 | 331 | // failing specs UI 332 | if (isUndefined(this.failedAlert)) { 333 | this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"}); 334 | } 335 | this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount); 336 | 337 | if (this.failedCount === 1 && isDefined(dom.alert)) { 338 | dom.alert.appendChild(this.failedAlert); 339 | dom.alert.appendChild(this.resultsMenu); 340 | } 341 | 342 | // summary info 343 | this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount); 344 | this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing"; 345 | }; 346 | 347 | this.complete = function() { 348 | dom.alert.removeChild(this.runningAlert); 349 | 350 | this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; 351 | 352 | if (this.failedCount === 0) { 353 | dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount))); 354 | } else { 355 | showDetails(); 356 | } 357 | 358 | dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s")); 359 | }; 360 | 361 | return this; 362 | 363 | function showDetails() { 364 | if (dom.reporter.className.search(/showDetails/) === -1) { 365 | dom.reporter.className += " showDetails"; 366 | } 367 | } 368 | 369 | function isUndefined(obj) { 370 | return typeof obj === 'undefined'; 371 | } 372 | 373 | function isDefined(obj) { 374 | return !isUndefined(obj); 375 | } 376 | 377 | function specPluralizedFor(count) { 378 | var str = count + " spec"; 379 | if (count > 1) { 380 | str += "s" 381 | } 382 | return str; 383 | } 384 | 385 | }; 386 | 387 | jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView); 388 | 389 | 390 | jasmine.HtmlReporter.SpecView = function(spec, dom, views) { 391 | this.spec = spec; 392 | this.dom = dom; 393 | this.views = views; 394 | 395 | this.symbol = this.createDom('li', { className: 'pending' }); 396 | this.dom.symbolSummary.appendChild(this.symbol); 397 | 398 | this.summary = this.createDom('div', { className: 'specSummary' }, 399 | this.createDom('a', { 400 | className: 'description', 401 | href: jasmine.HtmlReporter.sectionLink(this.spec.getFullName()), 402 | title: this.spec.getFullName() 403 | }, this.spec.description) 404 | ); 405 | 406 | this.detail = this.createDom('div', { className: 'specDetail' }, 407 | this.createDom('a', { 408 | className: 'description', 409 | href: '?spec=' + encodeURIComponent(this.spec.getFullName()), 410 | title: this.spec.getFullName() 411 | }, this.spec.getFullName()) 412 | ); 413 | }; 414 | 415 | jasmine.HtmlReporter.SpecView.prototype.status = function() { 416 | return this.getSpecStatus(this.spec); 417 | }; 418 | 419 | jasmine.HtmlReporter.SpecView.prototype.refresh = function() { 420 | this.symbol.className = this.status(); 421 | 422 | switch (this.status()) { 423 | case 'skipped': 424 | break; 425 | 426 | case 'passed': 427 | this.appendSummaryToSuiteDiv(); 428 | break; 429 | 430 | case 'failed': 431 | this.appendSummaryToSuiteDiv(); 432 | this.appendFailureDetail(); 433 | break; 434 | } 435 | }; 436 | 437 | jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() { 438 | this.summary.className += ' ' + this.status(); 439 | this.appendToSummary(this.spec, this.summary); 440 | }; 441 | 442 | jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() { 443 | this.detail.className += ' ' + this.status(); 444 | 445 | var resultItems = this.spec.results().getItems(); 446 | var messagesDiv = this.createDom('div', { className: 'messages' }); 447 | 448 | for (var i = 0; i < resultItems.length; i++) { 449 | var result = resultItems[i]; 450 | 451 | if (result.type == 'log') { 452 | messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); 453 | } else if (result.type == 'expect' && result.passed && !result.passed()) { 454 | messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); 455 | 456 | if (result.trace.stack) { 457 | messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); 458 | } 459 | } 460 | } 461 | 462 | if (messagesDiv.childNodes.length > 0) { 463 | this.detail.appendChild(messagesDiv); 464 | this.dom.details.appendChild(this.detail); 465 | } 466 | }; 467 | 468 | jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { 469 | this.suite = suite; 470 | this.dom = dom; 471 | this.views = views; 472 | 473 | this.element = this.createDom('div', { className: 'suite' }, 474 | this.createDom('a', { className: 'description', href: jasmine.HtmlReporter.sectionLink(this.suite.getFullName()) }, this.suite.description) 475 | ); 476 | 477 | this.appendToSummary(this.suite, this.element); 478 | }; 479 | 480 | jasmine.HtmlReporter.SuiteView.prototype.status = function() { 481 | return this.getSpecStatus(this.suite); 482 | }; 483 | 484 | jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { 485 | this.element.className += " " + this.status(); 486 | }; 487 | 488 | jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView); 489 | 490 | /* @deprecated Use jasmine.HtmlReporter instead 491 | */ 492 | jasmine.TrivialReporter = function(doc) { 493 | this.document = doc || document; 494 | this.suiteDivs = {}; 495 | this.logRunningSpecs = false; 496 | }; 497 | 498 | jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { 499 | var el = document.createElement(type); 500 | 501 | for (var i = 2; i < arguments.length; i++) { 502 | var child = arguments[i]; 503 | 504 | if (typeof child === 'string') { 505 | el.appendChild(document.createTextNode(child)); 506 | } else { 507 | if (child) { el.appendChild(child); } 508 | } 509 | } 510 | 511 | for (var attr in attrs) { 512 | if (attr == "className") { 513 | el[attr] = attrs[attr]; 514 | } else { 515 | el.setAttribute(attr, attrs[attr]); 516 | } 517 | } 518 | 519 | return el; 520 | }; 521 | 522 | jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { 523 | var showPassed, showSkipped; 524 | 525 | this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' }, 526 | this.createDom('div', { className: 'banner' }, 527 | this.createDom('div', { className: 'logo' }, 528 | this.createDom('span', { className: 'title' }, "Jasmine"), 529 | this.createDom('span', { className: 'version' }, runner.env.versionString())), 530 | this.createDom('div', { className: 'options' }, 531 | "Show ", 532 | showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), 533 | this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), 534 | showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), 535 | this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") 536 | ) 537 | ), 538 | 539 | this.runnerDiv = this.createDom('div', { className: 'runner running' }, 540 | this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), 541 | this.runnerMessageSpan = this.createDom('span', {}, "Running..."), 542 | this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) 543 | ); 544 | 545 | this.document.body.appendChild(this.outerDiv); 546 | 547 | var suites = runner.suites(); 548 | for (var i = 0; i < suites.length; i++) { 549 | var suite = suites[i]; 550 | var suiteDiv = this.createDom('div', { className: 'suite' }, 551 | this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), 552 | this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); 553 | this.suiteDivs[suite.id] = suiteDiv; 554 | var parentDiv = this.outerDiv; 555 | if (suite.parentSuite) { 556 | parentDiv = this.suiteDivs[suite.parentSuite.id]; 557 | } 558 | parentDiv.appendChild(suiteDiv); 559 | } 560 | 561 | this.startedAt = new Date(); 562 | 563 | var self = this; 564 | showPassed.onclick = function(evt) { 565 | if (showPassed.checked) { 566 | self.outerDiv.className += ' show-passed'; 567 | } else { 568 | self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); 569 | } 570 | }; 571 | 572 | showSkipped.onclick = function(evt) { 573 | if (showSkipped.checked) { 574 | self.outerDiv.className += ' show-skipped'; 575 | } else { 576 | self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); 577 | } 578 | }; 579 | }; 580 | 581 | jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { 582 | var results = runner.results(); 583 | var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; 584 | this.runnerDiv.setAttribute("class", className); 585 | //do it twice for IE 586 | this.runnerDiv.setAttribute("className", className); 587 | var specs = runner.specs(); 588 | var specCount = 0; 589 | for (var i = 0; i < specs.length; i++) { 590 | if (this.specFilter(specs[i])) { 591 | specCount++; 592 | } 593 | } 594 | var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); 595 | message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; 596 | this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); 597 | 598 | this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); 599 | }; 600 | 601 | jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { 602 | var results = suite.results(); 603 | var status = results.passed() ? 'passed' : 'failed'; 604 | if (results.totalCount === 0) { // todo: change this to check results.skipped 605 | status = 'skipped'; 606 | } 607 | this.suiteDivs[suite.id].className += " " + status; 608 | }; 609 | 610 | jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { 611 | if (this.logRunningSpecs) { 612 | this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); 613 | } 614 | }; 615 | 616 | jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { 617 | var results = spec.results(); 618 | var status = results.passed() ? 'passed' : 'failed'; 619 | if (results.skipped) { 620 | status = 'skipped'; 621 | } 622 | var specDiv = this.createDom('div', { className: 'spec ' + status }, 623 | this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), 624 | this.createDom('a', { 625 | className: 'description', 626 | href: '?spec=' + encodeURIComponent(spec.getFullName()), 627 | title: spec.getFullName() 628 | }, spec.description)); 629 | 630 | 631 | var resultItems = results.getItems(); 632 | var messagesDiv = this.createDom('div', { className: 'messages' }); 633 | for (var i = 0; i < resultItems.length; i++) { 634 | var result = resultItems[i]; 635 | 636 | if (result.type == 'log') { 637 | messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); 638 | } else if (result.type == 'expect' && result.passed && !result.passed()) { 639 | messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); 640 | 641 | if (result.trace.stack) { 642 | messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); 643 | } 644 | } 645 | } 646 | 647 | if (messagesDiv.childNodes.length > 0) { 648 | specDiv.appendChild(messagesDiv); 649 | } 650 | 651 | this.suiteDivs[spec.suite.id].appendChild(specDiv); 652 | }; 653 | 654 | jasmine.TrivialReporter.prototype.log = function() { 655 | var console = jasmine.getGlobal().console; 656 | if (console && console.log) { 657 | if (console.log.apply) { 658 | console.log.apply(console, arguments); 659 | } else { 660 | console.log(arguments); // ie fix: console.log.apply doesn't exist on ie 661 | } 662 | } 663 | }; 664 | 665 | jasmine.TrivialReporter.prototype.getLocation = function() { 666 | return this.document.location; 667 | }; 668 | 669 | jasmine.TrivialReporter.prototype.specFilter = function(spec) { 670 | var paramMap = {}; 671 | var params = this.getLocation().search.substring(1).split('&'); 672 | for (var i = 0; i < params.length; i++) { 673 | var p = params[i].split('='); 674 | paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); 675 | } 676 | 677 | if (!paramMap.spec) { 678 | return true; 679 | } 680 | return spec.getFullName().indexOf(paramMap.spec) === 0; 681 | }; 682 | -------------------------------------------------------------------------------- /lib/jasmine-1.3.1/jasmine.css: -------------------------------------------------------------------------------- 1 | body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; } 2 | 3 | #HTMLReporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; } 4 | #HTMLReporter a { text-decoration: none; } 5 | #HTMLReporter a:hover { text-decoration: underline; } 6 | #HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 { margin: 0; line-height: 14px; } 7 | #HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace { padding-left: 9px; padding-right: 9px; } 8 | #HTMLReporter #jasmine_content { position: fixed; right: 100%; } 9 | #HTMLReporter .version { color: #aaaaaa; } 10 | #HTMLReporter .banner { margin-top: 14px; } 11 | #HTMLReporter .duration { color: #aaaaaa; float: right; } 12 | #HTMLReporter .symbolSummary { overflow: hidden; *zoom: 1; margin: 14px 0; } 13 | #HTMLReporter .symbolSummary li { display: block; float: left; height: 7px; width: 14px; margin-bottom: 7px; font-size: 16px; } 14 | #HTMLReporter .symbolSummary li.passed { font-size: 14px; } 15 | #HTMLReporter .symbolSummary li.passed:before { color: #5e7d00; content: "\02022"; } 16 | #HTMLReporter .symbolSummary li.failed { line-height: 9px; } 17 | #HTMLReporter .symbolSummary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; } 18 | #HTMLReporter .symbolSummary li.skipped { font-size: 14px; } 19 | #HTMLReporter .symbolSummary li.skipped:before { color: #bababa; content: "\02022"; } 20 | #HTMLReporter .symbolSummary li.pending { line-height: 11px; } 21 | #HTMLReporter .symbolSummary li.pending:before { color: #aaaaaa; content: "-"; } 22 | #HTMLReporter .exceptions { color: #fff; float: right; margin-top: 5px; margin-right: 5px; } 23 | #HTMLReporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } 24 | #HTMLReporter .runningAlert { background-color: #666666; } 25 | #HTMLReporter .skippedAlert { background-color: #aaaaaa; } 26 | #HTMLReporter .skippedAlert:first-child { background-color: #333333; } 27 | #HTMLReporter .skippedAlert:hover { text-decoration: none; color: white; text-decoration: underline; } 28 | #HTMLReporter .passingAlert { background-color: #a6b779; } 29 | #HTMLReporter .passingAlert:first-child { background-color: #5e7d00; } 30 | #HTMLReporter .failingAlert { background-color: #cf867e; } 31 | #HTMLReporter .failingAlert:first-child { background-color: #b03911; } 32 | #HTMLReporter .results { margin-top: 14px; } 33 | #HTMLReporter #details { display: none; } 34 | #HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a { background-color: #fff; color: #333333; } 35 | #HTMLReporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; } 36 | #HTMLReporter.showDetails .summaryMenuItem:hover { text-decoration: underline; } 37 | #HTMLReporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; } 38 | #HTMLReporter.showDetails .summary { display: none; } 39 | #HTMLReporter.showDetails #details { display: block; } 40 | #HTMLReporter .summaryMenuItem { font-weight: bold; text-decoration: underline; } 41 | #HTMLReporter .summary { margin-top: 14px; } 42 | #HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary { margin-left: 14px; } 43 | #HTMLReporter .summary .specSummary.passed a { color: #5e7d00; } 44 | #HTMLReporter .summary .specSummary.failed a { color: #b03911; } 45 | #HTMLReporter .description + .suite { margin-top: 0; } 46 | #HTMLReporter .suite { margin-top: 14px; } 47 | #HTMLReporter .suite a { color: #333333; } 48 | #HTMLReporter #details .specDetail { margin-bottom: 28px; } 49 | #HTMLReporter #details .specDetail .description { display: block; color: white; background-color: #b03911; } 50 | #HTMLReporter .resultMessage { padding-top: 14px; color: #333333; } 51 | #HTMLReporter .resultMessage span.result { display: block; } 52 | #HTMLReporter .stackTrace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; } 53 | 54 | #TrivialReporter { padding: 8px 13px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow-y: scroll; background-color: white; font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ } 55 | #TrivialReporter a:visited, #TrivialReporter a { color: #303; } 56 | #TrivialReporter a:hover, #TrivialReporter a:active { color: blue; } 57 | #TrivialReporter .run_spec { float: right; padding-right: 5px; font-size: .8em; text-decoration: none; } 58 | #TrivialReporter .banner { color: #303; background-color: #fef; padding: 5px; } 59 | #TrivialReporter .logo { float: left; font-size: 1.1em; padding-left: 5px; } 60 | #TrivialReporter .logo .version { font-size: .6em; padding-left: 1em; } 61 | #TrivialReporter .runner.running { background-color: yellow; } 62 | #TrivialReporter .options { text-align: right; font-size: .8em; } 63 | #TrivialReporter .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; } 64 | #TrivialReporter .suite .suite { margin: 5px; } 65 | #TrivialReporter .suite.passed { background-color: #dfd; } 66 | #TrivialReporter .suite.failed { background-color: #fdd; } 67 | #TrivialReporter .spec { margin: 5px; padding-left: 1em; clear: both; } 68 | #TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped { padding-bottom: 5px; border: 1px solid gray; } 69 | #TrivialReporter .spec.failed { background-color: #fbb; border-color: red; } 70 | #TrivialReporter .spec.passed { background-color: #bfb; border-color: green; } 71 | #TrivialReporter .spec.skipped { background-color: #bbb; } 72 | #TrivialReporter .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; } 73 | #TrivialReporter .passed { background-color: #cfc; display: none; } 74 | #TrivialReporter .failed { background-color: #fbb; } 75 | #TrivialReporter .skipped { color: #777; background-color: #eee; display: none; } 76 | #TrivialReporter .resultMessage span.result { display: block; line-height: 2em; color: black; } 77 | #TrivialReporter .resultMessage .mismatch { color: black; } 78 | #TrivialReporter .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; } 79 | #TrivialReporter .finished-at { padding-left: 1em; font-size: .6em; } 80 | #TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped { display: block; } 81 | #TrivialReporter #jasmine_content { position: fixed; right: 100%; } 82 | #TrivialReporter .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; } 83 | -------------------------------------------------------------------------------- /lib/jasmine-2.0.0/boot.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2008-2013 Pivotal Labs 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining 5 | a copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 19 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 21 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | */ 23 | /** 24 | Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. 25 | 26 | If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. 27 | 28 | The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. 29 | 30 | [jasmine-gem]: http://github.com/pivotal/jasmine-gem 31 | */ 32 | 33 | (function() { 34 | 35 | /** 36 | * ## Require & Instantiate 37 | * 38 | * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. 39 | */ 40 | window.jasmine = jasmineRequire.core(jasmineRequire); 41 | 42 | /** 43 | * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. 44 | */ 45 | jasmineRequire.html(jasmine); 46 | 47 | /** 48 | * Create the Jasmine environment. This is used to run all specs in a project. 49 | */ 50 | var env = jasmine.getEnv(); 51 | 52 | /** 53 | * ## The Global Interface 54 | * 55 | * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. 56 | */ 57 | var jasmineInterface = { 58 | describe: function(description, specDefinitions) { 59 | return env.describe(description, specDefinitions); 60 | }, 61 | 62 | xdescribe: function(description, specDefinitions) { 63 | return env.xdescribe(description, specDefinitions); 64 | }, 65 | 66 | it: function(desc, func) { 67 | return env.it(desc, func); 68 | }, 69 | 70 | xit: function(desc, func) { 71 | return env.xit(desc, func); 72 | }, 73 | 74 | beforeEach: function(beforeEachFunction) { 75 | return env.beforeEach(beforeEachFunction); 76 | }, 77 | 78 | afterEach: function(afterEachFunction) { 79 | return env.afterEach(afterEachFunction); 80 | }, 81 | 82 | expect: function(actual) { 83 | return env.expect(actual); 84 | }, 85 | 86 | pending: function() { 87 | return env.pending(); 88 | }, 89 | 90 | spyOn: function(obj, methodName) { 91 | return env.spyOn(obj, methodName); 92 | }, 93 | 94 | jsApiReporter: new jasmine.JsApiReporter({ 95 | timer: new jasmine.Timer() 96 | }) 97 | }; 98 | 99 | /** 100 | * Add all of the Jasmine global/public interface to the proper global, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. 101 | */ 102 | if (typeof window == "undefined" && typeof exports == "object") { 103 | extend(exports, jasmineInterface); 104 | } else { 105 | extend(window, jasmineInterface); 106 | } 107 | 108 | /** 109 | * Expose the interface for adding custom equality testers. 110 | */ 111 | jasmine.addCustomEqualityTester = function(tester) { 112 | env.addCustomEqualityTester(tester); 113 | }; 114 | 115 | /** 116 | * Expose the interface for adding custom expectation matchers 117 | */ 118 | jasmine.addMatchers = function(matchers) { 119 | return env.addMatchers(matchers); 120 | }; 121 | 122 | /** 123 | * Expose the mock interface for the JavaScript timeout functions 124 | */ 125 | jasmine.clock = function() { 126 | return env.clock; 127 | }; 128 | 129 | /** 130 | * ## Runner Parameters 131 | * 132 | * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. 133 | */ 134 | 135 | var queryString = new jasmine.QueryString({ 136 | getWindowLocation: function() { return window.location; } 137 | }); 138 | 139 | var catchingExceptions = queryString.getParam("catch"); 140 | env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions); 141 | 142 | /** 143 | * ## Reporters 144 | * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). 145 | */ 146 | var htmlReporter = new jasmine.HtmlReporter({ 147 | env: env, 148 | onRaiseExceptionsClick: function() { queryString.setParam("catch", !env.catchingExceptions()); }, 149 | getContainer: function() { return document.body; }, 150 | createElement: function() { return document.createElement.apply(document, arguments); }, 151 | createTextNode: function() { return document.createTextNode.apply(document, arguments); }, 152 | timer: new jasmine.Timer() 153 | }); 154 | 155 | /** 156 | * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. 157 | */ 158 | env.addReporter(jasmineInterface.jsApiReporter); 159 | env.addReporter(htmlReporter); 160 | 161 | /** 162 | * Filter which specs will be run by matching the start of the full name against the `spec` query param. 163 | */ 164 | var specFilter = new jasmine.HtmlSpecFilter({ 165 | filterString: function() { return queryString.getParam("spec"); } 166 | }); 167 | 168 | env.specFilter = function(spec) { 169 | return specFilter.matches(spec.getFullName()); 170 | }; 171 | 172 | /** 173 | * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. 174 | */ 175 | window.setTimeout = window.setTimeout; 176 | window.setInterval = window.setInterval; 177 | window.clearTimeout = window.clearTimeout; 178 | window.clearInterval = window.clearInterval; 179 | 180 | /** 181 | * ## Execution 182 | * 183 | * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. 184 | */ 185 | var currentWindowOnload = window.onload; 186 | 187 | window.onload = function() { 188 | if (currentWindowOnload) { 189 | currentWindowOnload(); 190 | } 191 | htmlReporter.initialize(); 192 | env.execute(); 193 | }; 194 | 195 | /** 196 | * Helper function for readability above. 197 | */ 198 | function extend(destination, source) { 199 | for (var property in source) destination[property] = source[property]; 200 | return destination; 201 | } 202 | 203 | }()); 204 | -------------------------------------------------------------------------------- /lib/jasmine-2.0.0/jasmine-html.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2008-2013 Pivotal Labs 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining 5 | a copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 19 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 21 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | */ 23 | jasmineRequire.html = function(j$) { 24 | j$.ResultsNode = jasmineRequire.ResultsNode(); 25 | j$.HtmlReporter = jasmineRequire.HtmlReporter(j$); 26 | j$.QueryString = jasmineRequire.QueryString(); 27 | j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter(); 28 | }; 29 | 30 | jasmineRequire.HtmlReporter = function(j$) { 31 | 32 | var noopTimer = { 33 | start: function() {}, 34 | elapsed: function() { return 0; } 35 | }; 36 | 37 | function HtmlReporter(options) { 38 | var env = options.env || {}, 39 | getContainer = options.getContainer, 40 | createElement = options.createElement, 41 | createTextNode = options.createTextNode, 42 | onRaiseExceptionsClick = options.onRaiseExceptionsClick || function() {}, 43 | timer = options.timer || noopTimer, 44 | results = [], 45 | specsExecuted = 0, 46 | failureCount = 0, 47 | pendingSpecCount = 0, 48 | htmlReporterMain, 49 | symbols; 50 | 51 | this.initialize = function() { 52 | htmlReporterMain = createDom("div", {className: "html-reporter"}, 53 | createDom("div", {className: "banner"}, 54 | createDom("span", {className: "title"}, "Jasmine"), 55 | createDom("span", {className: "version"}, j$.version) 56 | ), 57 | createDom("ul", {className: "symbol-summary"}), 58 | createDom("div", {className: "alert"}), 59 | createDom("div", {className: "results"}, 60 | createDom("div", {className: "failures"}) 61 | ) 62 | ); 63 | getContainer().appendChild(htmlReporterMain); 64 | 65 | symbols = find(".symbol-summary"); 66 | }; 67 | 68 | var totalSpecsDefined; 69 | this.jasmineStarted = function(options) { 70 | totalSpecsDefined = options.totalSpecsDefined || 0; 71 | timer.start(); 72 | }; 73 | 74 | var summary = createDom("div", {className: "summary"}); 75 | 76 | var topResults = new j$.ResultsNode({}, "", null), 77 | currentParent = topResults; 78 | 79 | this.suiteStarted = function(result) { 80 | currentParent.addChild(result, "suite"); 81 | currentParent = currentParent.last(); 82 | }; 83 | 84 | this.suiteDone = function(result) { 85 | if (currentParent == topResults) { 86 | return; 87 | } 88 | 89 | currentParent = currentParent.parent; 90 | }; 91 | 92 | this.specStarted = function(result) { 93 | currentParent.addChild(result, "spec"); 94 | }; 95 | 96 | var failures = []; 97 | this.specDone = function(result) { 98 | if (result.status != "disabled") { 99 | specsExecuted++; 100 | } 101 | 102 | symbols.appendChild(createDom("li", { 103 | className: result.status, 104 | id: "spec_" + result.id, 105 | title: result.fullName 106 | } 107 | )); 108 | 109 | if (result.status == "failed") { 110 | failureCount++; 111 | 112 | var failure = 113 | createDom("div", {className: "spec-detail failed"}, 114 | createDom("div", {className: "description"}, 115 | createDom("a", {title: result.fullName, href: specHref(result)}, result.fullName) 116 | ), 117 | createDom("div", {className: "messages"}) 118 | ); 119 | var messages = failure.childNodes[1]; 120 | 121 | for (var i = 0; i < result.failedExpectations.length; i++) { 122 | var expectation = result.failedExpectations[i]; 123 | messages.appendChild(createDom("div", {className: "result-message"}, expectation.message)); 124 | messages.appendChild(createDom("div", {className: "stack-trace"}, expectation.stack)); 125 | } 126 | 127 | failures.push(failure); 128 | } 129 | 130 | if (result.status == "pending") { 131 | pendingSpecCount++; 132 | } 133 | }; 134 | 135 | this.jasmineDone = function() { 136 | var banner = find(".banner"); 137 | banner.appendChild(createDom("span", {className: "duration"}, "finished in " + timer.elapsed() / 1000 + "s")); 138 | 139 | var alert = find(".alert"); 140 | 141 | alert.appendChild(createDom("span", { className: "exceptions" }, 142 | createDom("label", { className: "label", 'for': "raise-exceptions" }, "raise exceptions"), 143 | createDom("input", { 144 | className: "raise", 145 | id: "raise-exceptions", 146 | type: "checkbox" 147 | }) 148 | )); 149 | var checkbox = find("input"); 150 | 151 | checkbox.checked = !env.catchingExceptions(); 152 | checkbox.onclick = onRaiseExceptionsClick; 153 | 154 | if (specsExecuted < totalSpecsDefined) { 155 | var skippedMessage = "Ran " + specsExecuted + " of " + totalSpecsDefined + " specs - run all"; 156 | alert.appendChild( 157 | createDom("span", {className: "bar skipped"}, 158 | createDom("a", {href: "?", title: "Run all specs"}, skippedMessage) 159 | ) 160 | ); 161 | } 162 | var statusBarMessage = "" + pluralize("spec", specsExecuted) + ", " + pluralize("failure", failureCount); 163 | if (pendingSpecCount) { statusBarMessage += ", " + pluralize("pending spec", pendingSpecCount); } 164 | 165 | var statusBarClassName = "bar " + ((failureCount > 0) ? "failed" : "passed"); 166 | alert.appendChild(createDom("span", {className: statusBarClassName}, statusBarMessage)); 167 | 168 | var results = find(".results"); 169 | results.appendChild(summary); 170 | 171 | summaryList(topResults, summary); 172 | 173 | function summaryList(resultsTree, domParent) { 174 | var specListNode; 175 | for (var i = 0; i < resultsTree.children.length; i++) { 176 | var resultNode = resultsTree.children[i]; 177 | if (resultNode.type == "suite") { 178 | var suiteListNode = createDom("ul", {className: "suite", id: "suite-" + resultNode.result.id}, 179 | createDom("li", {className: "suite-detail"}, 180 | createDom("a", {href: specHref(resultNode.result)}, resultNode.result.description) 181 | ) 182 | ); 183 | 184 | summaryList(resultNode, suiteListNode); 185 | domParent.appendChild(suiteListNode); 186 | } 187 | if (resultNode.type == "spec") { 188 | if (domParent.getAttribute("class") != "specs") { 189 | specListNode = createDom("ul", {className: "specs"}); 190 | domParent.appendChild(specListNode); 191 | } 192 | specListNode.appendChild( 193 | createDom("li", { 194 | className: resultNode.result.status, 195 | id: "spec-" + resultNode.result.id 196 | }, 197 | createDom("a", {href: specHref(resultNode.result)}, resultNode.result.description) 198 | ) 199 | ); 200 | } 201 | } 202 | } 203 | 204 | if (failures.length) { 205 | alert.appendChild( 206 | createDom('span', {className: "menu bar spec-list"}, 207 | createDom("span", {}, "Spec List | "), 208 | createDom('a', {className: "failures-menu", href: "#"}, "Failures"))); 209 | alert.appendChild( 210 | createDom('span', {className: "menu bar failure-list"}, 211 | createDom('a', {className: "spec-list-menu", href: "#"}, "Spec List"), 212 | createDom("span", {}, " | Failures "))); 213 | 214 | find(".failures-menu").onclick = function() { 215 | setMenuModeTo('failure-list'); 216 | }; 217 | find(".spec-list-menu").onclick = function() { 218 | setMenuModeTo('spec-list'); 219 | }; 220 | 221 | setMenuModeTo('failure-list'); 222 | 223 | var failureNode = find(".failures"); 224 | for (var i = 0; i < failures.length; i++) { 225 | failureNode.appendChild(failures[i]); 226 | } 227 | } 228 | }; 229 | 230 | return this; 231 | 232 | function find(selector) { 233 | return getContainer().querySelector(selector); 234 | } 235 | 236 | function createDom(type, attrs, childrenVarArgs) { 237 | var el = createElement(type); 238 | 239 | for (var i = 2; i < arguments.length; i++) { 240 | var child = arguments[i]; 241 | 242 | if (typeof child === 'string') { 243 | el.appendChild(createTextNode(child)); 244 | } else { 245 | if (child) { 246 | el.appendChild(child); 247 | } 248 | } 249 | } 250 | 251 | for (var attr in attrs) { 252 | if (attr == "className") { 253 | el[attr] = attrs[attr]; 254 | } else { 255 | el.setAttribute(attr, attrs[attr]); 256 | } 257 | } 258 | 259 | return el; 260 | } 261 | 262 | function pluralize(singular, count) { 263 | var word = (count == 1 ? singular : singular + "s"); 264 | 265 | return "" + count + " " + word; 266 | } 267 | 268 | function specHref(result) { 269 | return "?spec=" + encodeURIComponent(result.fullName); 270 | } 271 | 272 | function setMenuModeTo(mode) { 273 | htmlReporterMain.setAttribute("class", "html-reporter " + mode); 274 | } 275 | } 276 | 277 | return HtmlReporter; 278 | }; 279 | 280 | jasmineRequire.HtmlSpecFilter = function() { 281 | function HtmlSpecFilter(options) { 282 | var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 283 | var filterPattern = new RegExp(filterString); 284 | 285 | this.matches = function(specName) { 286 | return filterPattern.test(specName); 287 | }; 288 | } 289 | 290 | return HtmlSpecFilter; 291 | }; 292 | 293 | jasmineRequire.ResultsNode = function() { 294 | function ResultsNode(result, type, parent) { 295 | this.result = result; 296 | this.type = type; 297 | this.parent = parent; 298 | 299 | this.children = []; 300 | 301 | this.addChild = function(result, type) { 302 | this.children.push(new ResultsNode(result, type, this)); 303 | }; 304 | 305 | this.last = function() { 306 | return this.children[this.children.length - 1]; 307 | }; 308 | } 309 | 310 | return ResultsNode; 311 | }; 312 | 313 | jasmineRequire.QueryString = function() { 314 | function QueryString(options) { 315 | 316 | this.setParam = function(key, value) { 317 | var paramMap = queryStringToParamMap(); 318 | paramMap[key] = value; 319 | options.getWindowLocation().search = toQueryString(paramMap); 320 | }; 321 | 322 | this.getParam = function(key) { 323 | return queryStringToParamMap()[key]; 324 | }; 325 | 326 | return this; 327 | 328 | function toQueryString(paramMap) { 329 | var qStrPairs = []; 330 | for (var prop in paramMap) { 331 | qStrPairs.push(encodeURIComponent(prop) + "=" + encodeURIComponent(paramMap[prop])); 332 | } 333 | return "?" + qStrPairs.join('&'); 334 | } 335 | 336 | function queryStringToParamMap() { 337 | var paramStr = options.getWindowLocation().search.substring(1), 338 | params = [], 339 | paramMap = {}; 340 | 341 | if (paramStr.length > 0) { 342 | params = paramStr.split('&'); 343 | for (var i = 0; i < params.length; i++) { 344 | var p = params[i].split('='); 345 | var value = decodeURIComponent(p[1]); 346 | if (value === "true" || value === "false") { 347 | value = JSON.parse(value); 348 | } 349 | paramMap[decodeURIComponent(p[0])] = value; 350 | } 351 | } 352 | 353 | return paramMap; 354 | } 355 | 356 | } 357 | 358 | return QueryString; 359 | }; 360 | -------------------------------------------------------------------------------- /lib/jasmine-2.0.0/jasmine.css: -------------------------------------------------------------------------------- 1 | body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; } 2 | 3 | .html-reporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; } 4 | .html-reporter a { text-decoration: none; } 5 | .html-reporter a:hover { text-decoration: underline; } 6 | .html-reporter p, .html-reporter h1, .html-reporter h2, .html-reporter h3, .html-reporter h4, .html-reporter h5, .html-reporter h6 { margin: 0; line-height: 14px; } 7 | .html-reporter .banner, .html-reporter .symbol-summary, .html-reporter .summary, .html-reporter .result-message, .html-reporter .spec .description, .html-reporter .spec-detail .description, .html-reporter .alert .bar, .html-reporter .stack-trace { padding-left: 9px; padding-right: 9px; } 8 | .html-reporter .banner .version { margin-left: 14px; } 9 | .html-reporter #jasmine_content { position: fixed; right: 100%; } 10 | .html-reporter .version { color: #aaaaaa; } 11 | .html-reporter .banner { margin-top: 14px; } 12 | .html-reporter .duration { color: #aaaaaa; float: right; } 13 | .html-reporter .symbol-summary { overflow: hidden; *zoom: 1; margin: 14px 0; } 14 | .html-reporter .symbol-summary li { display: inline-block; height: 8px; width: 14px; font-size: 16px; } 15 | .html-reporter .symbol-summary li.passed { font-size: 14px; } 16 | .html-reporter .symbol-summary li.passed:before { color: #5e7d00; content: "\02022"; } 17 | .html-reporter .symbol-summary li.failed { line-height: 9px; } 18 | .html-reporter .symbol-summary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; } 19 | .html-reporter .symbol-summary li.disabled { font-size: 14px; } 20 | .html-reporter .symbol-summary li.disabled:before { color: #bababa; content: "\02022"; } 21 | .html-reporter .symbol-summary li.pending { line-height: 17px; } 22 | .html-reporter .symbol-summary li.pending:before { color: #ba9d37; content: "*"; } 23 | .html-reporter .exceptions { color: #fff; float: right; margin-top: 5px; margin-right: 5px; } 24 | .html-reporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } 25 | .html-reporter .bar.failed { background-color: #b03911; } 26 | .html-reporter .bar.passed { background-color: #a6b779; } 27 | .html-reporter .bar.skipped { background-color: #bababa; } 28 | .html-reporter .bar.menu { background-color: #fff; color: #aaaaaa; } 29 | .html-reporter .bar.menu a { color: #333333; } 30 | .html-reporter .bar a { color: white; } 31 | .html-reporter.spec-list .bar.menu.failure-list, .html-reporter.spec-list .results .failures { display: none; } 32 | .html-reporter.failure-list .bar.menu.spec-list, .html-reporter.failure-list .summary { display: none; } 33 | .html-reporter .running-alert { background-color: #666666; } 34 | .html-reporter .results { margin-top: 14px; } 35 | .html-reporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; } 36 | .html-reporter.showDetails .summaryMenuItem:hover { text-decoration: underline; } 37 | .html-reporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; } 38 | .html-reporter.showDetails .summary { display: none; } 39 | .html-reporter.showDetails #details { display: block; } 40 | .html-reporter .summaryMenuItem { font-weight: bold; text-decoration: underline; } 41 | .html-reporter .summary { margin-top: 14px; } 42 | .html-reporter .summary ul { list-style-type: none; margin-left: 14px; padding-top: 0; padding-left: 0; } 43 | .html-reporter .summary ul.suite { margin-top: 7px; margin-bottom: 7px; } 44 | .html-reporter .summary li.passed a { color: #5e7d00; } 45 | .html-reporter .summary li.failed a { color: #b03911; } 46 | .html-reporter .summary li.pending a { color: #ba9d37; } 47 | .html-reporter .description + .suite { margin-top: 0; } 48 | .html-reporter .suite { margin-top: 14px; } 49 | .html-reporter .suite a { color: #333333; } 50 | .html-reporter .failures .spec-detail { margin-bottom: 28px; } 51 | .html-reporter .failures .spec-detail .description { background-color: #b03911; } 52 | .html-reporter .failures .spec-detail .description a { color: white; } 53 | .html-reporter .result-message { padding-top: 14px; color: #333333; white-space: pre; } 54 | .html-reporter .result-message span.result { display: block; } 55 | .html-reporter .stack-trace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; } 56 | -------------------------------------------------------------------------------- /lib/jasmine-2.0.0/jasmine.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2008-2013 Pivotal Labs 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining 5 | a copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 19 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 21 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | */ 23 | function getJasmineRequireObj() { 24 | if (typeof module !== "undefined" && module.exports) { 25 | return exports; 26 | } else { 27 | window.jasmineRequire = window.jasmineRequire || {}; 28 | return window.jasmineRequire; 29 | } 30 | } 31 | 32 | getJasmineRequireObj().core = function(jRequire) { 33 | var j$ = {}; 34 | 35 | jRequire.base(j$); 36 | j$.util = jRequire.util(); 37 | j$.Any = jRequire.Any(); 38 | j$.CallTracker = jRequire.CallTracker(); 39 | j$.Clock = jRequire.Clock(); 40 | j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(); 41 | j$.Env = jRequire.Env(j$); 42 | j$.ExceptionFormatter = jRequire.ExceptionFormatter(); 43 | j$.Expectation = jRequire.Expectation(); 44 | j$.buildExpectationResult = jRequire.buildExpectationResult(); 45 | j$.JsApiReporter = jRequire.JsApiReporter(); 46 | j$.matchersUtil = jRequire.matchersUtil(j$); 47 | j$.ObjectContaining = jRequire.ObjectContaining(j$); 48 | j$.pp = jRequire.pp(j$); 49 | j$.QueueRunner = jRequire.QueueRunner(); 50 | j$.ReportDispatcher = jRequire.ReportDispatcher(); 51 | j$.Spec = jRequire.Spec(j$); 52 | j$.SpyStrategy = jRequire.SpyStrategy(); 53 | j$.Suite = jRequire.Suite(); 54 | j$.Timer = jRequire.Timer(); 55 | j$.version = jRequire.version(); 56 | 57 | j$.matchers = jRequire.requireMatchers(jRequire, j$); 58 | 59 | return j$; 60 | }; 61 | 62 | getJasmineRequireObj().requireMatchers = function(jRequire, j$) { 63 | var availableMatchers = [ 64 | "toBe", 65 | "toBeCloseTo", 66 | "toBeDefined", 67 | "toBeFalsy", 68 | "toBeGreaterThan", 69 | "toBeLessThan", 70 | "toBeNaN", 71 | "toBeNull", 72 | "toBeTruthy", 73 | "toBeUndefined", 74 | "toContain", 75 | "toEqual", 76 | "toHaveBeenCalled", 77 | "toHaveBeenCalledWith", 78 | "toMatch", 79 | "toThrow", 80 | "toThrowError" 81 | ], 82 | matchers = {}; 83 | 84 | for (var i = 0; i < availableMatchers.length; i++) { 85 | var name = availableMatchers[i]; 86 | matchers[name] = jRequire[name](j$); 87 | } 88 | 89 | return matchers; 90 | }; 91 | 92 | getJasmineRequireObj().base = function(j$) { 93 | j$.unimplementedMethod_ = function() { 94 | throw new Error("unimplemented method"); 95 | }; 96 | 97 | j$.MAX_PRETTY_PRINT_DEPTH = 40; 98 | j$.DEFAULT_TIMEOUT_INTERVAL = 5000; 99 | 100 | j$.getGlobal = (function() { 101 | var jasmineGlobal = eval.call(null, "this"); 102 | return function() { 103 | return jasmineGlobal; 104 | }; 105 | })(); 106 | 107 | j$.getEnv = function(options) { 108 | var env = j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options); 109 | //jasmine. singletons in here (setTimeout blah blah). 110 | return env; 111 | }; 112 | 113 | j$.isArray_ = function(value) { 114 | return j$.isA_("Array", value); 115 | }; 116 | 117 | j$.isString_ = function(value) { 118 | return j$.isA_("String", value); 119 | }; 120 | 121 | j$.isNumber_ = function(value) { 122 | return j$.isA_("Number", value); 123 | }; 124 | 125 | j$.isA_ = function(typeName, value) { 126 | return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; 127 | }; 128 | 129 | j$.isDomNode = function(obj) { 130 | return obj.nodeType > 0; 131 | }; 132 | 133 | j$.any = function(clazz) { 134 | return new j$.Any(clazz); 135 | }; 136 | 137 | j$.objectContaining = function(sample) { 138 | return new j$.ObjectContaining(sample); 139 | }; 140 | 141 | j$.createSpy = function(name, originalFn) { 142 | 143 | var spyStrategy = new j$.SpyStrategy({ 144 | name: name, 145 | fn: originalFn, 146 | getSpy: function() { return spy; } 147 | }), 148 | callTracker = new j$.CallTracker(), 149 | spy = function() { 150 | callTracker.track({ 151 | object: this, 152 | args: Array.prototype.slice.apply(arguments) 153 | }); 154 | return spyStrategy.exec.apply(this, arguments); 155 | }; 156 | 157 | for (var prop in originalFn) { 158 | if (prop === 'and' || prop === 'calls') { 159 | throw new Error("Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon"); 160 | } 161 | 162 | spy[prop] = originalFn[prop]; 163 | } 164 | 165 | spy.and = spyStrategy; 166 | spy.calls = callTracker; 167 | 168 | return spy; 169 | }; 170 | 171 | j$.isSpy = function(putativeSpy) { 172 | if (!putativeSpy) { 173 | return false; 174 | } 175 | return putativeSpy.and instanceof j$.SpyStrategy && 176 | putativeSpy.calls instanceof j$.CallTracker; 177 | }; 178 | 179 | j$.createSpyObj = function(baseName, methodNames) { 180 | if (!j$.isArray_(methodNames) || methodNames.length === 0) { 181 | throw "createSpyObj requires a non-empty array of method names to create spies for"; 182 | } 183 | var obj = {}; 184 | for (var i = 0; i < methodNames.length; i++) { 185 | obj[methodNames[i]] = j$.createSpy(baseName + '.' + methodNames[i]); 186 | } 187 | return obj; 188 | }; 189 | }; 190 | 191 | getJasmineRequireObj().util = function() { 192 | 193 | var util = {}; 194 | 195 | util.inherit = function(childClass, parentClass) { 196 | var Subclass = function() { 197 | }; 198 | Subclass.prototype = parentClass.prototype; 199 | childClass.prototype = new Subclass(); 200 | }; 201 | 202 | util.htmlEscape = function(str) { 203 | if (!str) { 204 | return str; 205 | } 206 | return str.replace(/&/g, '&') 207 | .replace(//g, '>'); 209 | }; 210 | 211 | util.argsToArray = function(args) { 212 | var arrayOfArgs = []; 213 | for (var i = 0; i < args.length; i++) { 214 | arrayOfArgs.push(args[i]); 215 | } 216 | return arrayOfArgs; 217 | }; 218 | 219 | util.isUndefined = function(obj) { 220 | return obj === void 0; 221 | }; 222 | 223 | return util; 224 | }; 225 | 226 | getJasmineRequireObj().Spec = function(j$) { 227 | function Spec(attrs) { 228 | this.expectationFactory = attrs.expectationFactory; 229 | this.resultCallback = attrs.resultCallback || function() {}; 230 | this.id = attrs.id; 231 | this.description = attrs.description || ''; 232 | this.fn = attrs.fn; 233 | this.beforeFns = attrs.beforeFns || function() { return []; }; 234 | this.afterFns = attrs.afterFns || function() { return []; }; 235 | this.onStart = attrs.onStart || function() {}; 236 | this.exceptionFormatter = attrs.exceptionFormatter || function() {}; 237 | this.getSpecName = attrs.getSpecName || function() { return ''; }; 238 | this.expectationResultFactory = attrs.expectationResultFactory || function() { }; 239 | this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; 240 | this.catchingExceptions = attrs.catchingExceptions || function() { return true; }; 241 | 242 | this.timer = attrs.timer || {setTimeout: setTimeout, clearTimeout: clearTimeout}; 243 | 244 | if (!this.fn) { 245 | this.pend(); 246 | } 247 | 248 | this.result = { 249 | id: this.id, 250 | description: this.description, 251 | fullName: this.getFullName(), 252 | failedExpectations: [] 253 | }; 254 | } 255 | 256 | Spec.prototype.addExpectationResult = function(passed, data) { 257 | if (passed) { 258 | return; 259 | } 260 | this.result.failedExpectations.push(this.expectationResultFactory(data)); 261 | }; 262 | 263 | Spec.prototype.expect = function(actual) { 264 | return this.expectationFactory(actual, this); 265 | }; 266 | 267 | Spec.prototype.execute = function(onComplete) { 268 | var self = this, 269 | timeout; 270 | 271 | this.onStart(this); 272 | 273 | if (this.markedPending || this.disabled) { 274 | complete(); 275 | return; 276 | } 277 | 278 | function timeoutable(fn) { 279 | return function(done) { 280 | timeout = Function.prototype.apply.apply(self.timer.setTimeout, [j$.getGlobal(), [function() { 281 | onException(new Error('Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.')); 282 | done(); 283 | }, j$.DEFAULT_TIMEOUT_INTERVAL]]); 284 | 285 | var callDone = function() { 286 | clearTimeoutable(); 287 | done(); 288 | }; 289 | 290 | fn.call(this, callDone); //TODO: do we care about more than 1 arg? 291 | }; 292 | } 293 | 294 | function clearTimeoutable() { 295 | Function.prototype.apply.apply(self.timer.clearTimeout, [j$.getGlobal(), [timeout]]); 296 | timeout = void 0; 297 | } 298 | 299 | var allFns = this.beforeFns().concat(this.fn).concat(this.afterFns()), 300 | allTimeoutableFns = []; 301 | for (var i = 0; i < allFns.length; i++) { 302 | var fn = allFns[i]; 303 | allTimeoutableFns.push(fn.length > 0 ? timeoutable(fn) : fn); 304 | } 305 | 306 | this.queueRunnerFactory({ 307 | fns: allTimeoutableFns, 308 | onException: onException, 309 | onComplete: complete 310 | }); 311 | 312 | function onException(e) { 313 | clearTimeoutable(); 314 | if (Spec.isPendingSpecException(e)) { 315 | self.pend(); 316 | return; 317 | } 318 | 319 | self.addExpectationResult(false, { 320 | matcherName: "", 321 | passed: false, 322 | expected: "", 323 | actual: "", 324 | error: e 325 | }); 326 | } 327 | 328 | function complete() { 329 | self.result.status = self.status(); 330 | self.resultCallback(self.result); 331 | 332 | if (onComplete) { 333 | onComplete(); 334 | } 335 | } 336 | }; 337 | 338 | Spec.prototype.disable = function() { 339 | this.disabled = true; 340 | }; 341 | 342 | Spec.prototype.pend = function() { 343 | this.markedPending = true; 344 | }; 345 | 346 | Spec.prototype.status = function() { 347 | if (this.disabled) { 348 | return 'disabled'; 349 | } 350 | 351 | if (this.markedPending) { 352 | return 'pending'; 353 | } 354 | 355 | if (this.result.failedExpectations.length > 0) { 356 | return 'failed'; 357 | } else { 358 | return 'passed'; 359 | } 360 | }; 361 | 362 | Spec.prototype.getFullName = function() { 363 | return this.getSpecName(this); 364 | }; 365 | 366 | Spec.pendingSpecExceptionMessage = "=> marked Pending"; 367 | 368 | Spec.isPendingSpecException = function(e) { 369 | return e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1; 370 | }; 371 | 372 | return Spec; 373 | }; 374 | 375 | if (typeof window == void 0 && typeof exports == "object") { 376 | exports.Spec = jasmineRequire.Spec; 377 | } 378 | 379 | getJasmineRequireObj().Env = function(j$) { 380 | function Env(options) { 381 | options = options || {}; 382 | 383 | var self = this; 384 | var global = options.global || j$.getGlobal(); 385 | 386 | var totalSpecsDefined = 0; 387 | 388 | var catchExceptions = true; 389 | 390 | var realSetTimeout = j$.getGlobal().setTimeout; 391 | var realClearTimeout = j$.getGlobal().clearTimeout; 392 | this.clock = new j$.Clock(global, new j$.DelayedFunctionScheduler()); 393 | 394 | var runnableLookupTable = {}; 395 | 396 | var spies = []; 397 | 398 | var currentSpec = null; 399 | var currentSuite = null; 400 | 401 | var reporter = new j$.ReportDispatcher([ 402 | "jasmineStarted", 403 | "jasmineDone", 404 | "suiteStarted", 405 | "suiteDone", 406 | "specStarted", 407 | "specDone" 408 | ]); 409 | 410 | this.specFilter = function() { 411 | return true; 412 | }; 413 | 414 | var equalityTesters = []; 415 | 416 | var customEqualityTesters = []; 417 | this.addCustomEqualityTester = function(tester) { 418 | customEqualityTesters.push(tester); 419 | }; 420 | 421 | j$.Expectation.addCoreMatchers(j$.matchers); 422 | 423 | var nextSpecId = 0; 424 | var getNextSpecId = function() { 425 | return 'spec' + nextSpecId++; 426 | }; 427 | 428 | var nextSuiteId = 0; 429 | var getNextSuiteId = function() { 430 | return 'suite' + nextSuiteId++; 431 | }; 432 | 433 | var expectationFactory = function(actual, spec) { 434 | return j$.Expectation.Factory({ 435 | util: j$.matchersUtil, 436 | customEqualityTesters: customEqualityTesters, 437 | actual: actual, 438 | addExpectationResult: addExpectationResult 439 | }); 440 | 441 | function addExpectationResult(passed, result) { 442 | return spec.addExpectationResult(passed, result); 443 | } 444 | }; 445 | 446 | var specStarted = function(spec) { 447 | currentSpec = spec; 448 | reporter.specStarted(spec.result); 449 | }; 450 | 451 | var beforeFns = function(suite) { 452 | return function() { 453 | var befores = []; 454 | while(suite) { 455 | befores = befores.concat(suite.beforeFns); 456 | suite = suite.parentSuite; 457 | } 458 | return befores.reverse(); 459 | }; 460 | }; 461 | 462 | var afterFns = function(suite) { 463 | return function() { 464 | var afters = []; 465 | while(suite) { 466 | afters = afters.concat(suite.afterFns); 467 | suite = suite.parentSuite; 468 | } 469 | return afters; 470 | }; 471 | }; 472 | 473 | var getSpecName = function(spec, suite) { 474 | return suite.getFullName() + ' ' + spec.description; 475 | }; 476 | 477 | // TODO: we may just be able to pass in the fn instead of wrapping here 478 | var buildExpectationResult = j$.buildExpectationResult, 479 | exceptionFormatter = new j$.ExceptionFormatter(), 480 | expectationResultFactory = function(attrs) { 481 | attrs.messageFormatter = exceptionFormatter.message; 482 | attrs.stackFormatter = exceptionFormatter.stack; 483 | 484 | return buildExpectationResult(attrs); 485 | }; 486 | 487 | // TODO: fix this naming, and here's where the value comes in 488 | this.catchExceptions = function(value) { 489 | catchExceptions = !!value; 490 | return catchExceptions; 491 | }; 492 | 493 | this.catchingExceptions = function() { 494 | return catchExceptions; 495 | }; 496 | 497 | var maximumSpecCallbackDepth = 20; 498 | var currentSpecCallbackDepth = 0; 499 | 500 | function clearStack(fn) { 501 | currentSpecCallbackDepth++; 502 | if (currentSpecCallbackDepth >= maximumSpecCallbackDepth) { 503 | currentSpecCallbackDepth = 0; 504 | realSetTimeout(fn, 0); 505 | } else { 506 | fn(); 507 | } 508 | } 509 | 510 | var catchException = function(e) { 511 | return j$.Spec.isPendingSpecException(e) || catchExceptions; 512 | }; 513 | 514 | var queueRunnerFactory = function(options) { 515 | options.catchException = catchException; 516 | options.clearStack = options.clearStack || clearStack; 517 | 518 | new j$.QueueRunner(options).execute(); 519 | }; 520 | 521 | var topSuite = new j$.Suite({ 522 | env: this, 523 | id: getNextSuiteId(), 524 | description: 'Jasmine__TopLevel__Suite', 525 | queueRunner: queueRunnerFactory, 526 | resultCallback: function() {} // TODO - hook this up 527 | }); 528 | runnableLookupTable[topSuite.id] = topSuite; 529 | currentSuite = topSuite; 530 | 531 | this.topSuite = function() { 532 | return topSuite; 533 | }; 534 | 535 | this.execute = function(runnablesToRun) { 536 | runnablesToRun = runnablesToRun || [topSuite.id]; 537 | 538 | var allFns = []; 539 | for(var i = 0; i < runnablesToRun.length; i++) { 540 | var runnable = runnableLookupTable[runnablesToRun[i]]; 541 | allFns.push((function(runnable) { return function(done) { runnable.execute(done); }; })(runnable)); 542 | } 543 | 544 | reporter.jasmineStarted({ 545 | totalSpecsDefined: totalSpecsDefined 546 | }); 547 | 548 | queueRunnerFactory({fns: allFns, onComplete: reporter.jasmineDone}); 549 | }; 550 | 551 | this.addReporter = function(reporterToAdd) { 552 | reporter.addReporter(reporterToAdd); 553 | }; 554 | 555 | this.addMatchers = function(matchersToAdd) { 556 | j$.Expectation.addMatchers(matchersToAdd); 557 | }; 558 | 559 | this.spyOn = function(obj, methodName) { 560 | if (j$.util.isUndefined(obj)) { 561 | throw new Error("spyOn could not find an object to spy upon for " + methodName + "()"); 562 | } 563 | 564 | if (j$.util.isUndefined(obj[methodName])) { 565 | throw new Error(methodName + '() method does not exist'); 566 | } 567 | 568 | if (obj[methodName] && j$.isSpy(obj[methodName])) { 569 | //TODO?: should this return the current spy? Downside: may cause user confusion about spy state 570 | throw new Error(methodName + ' has already been spied upon'); 571 | } 572 | 573 | var spy = j$.createSpy(methodName, obj[methodName]); 574 | 575 | spies.push({ 576 | spy: spy, 577 | baseObj: obj, 578 | methodName: methodName, 579 | originalValue: obj[methodName] 580 | }); 581 | 582 | obj[methodName] = spy; 583 | 584 | return spy; 585 | }; 586 | 587 | var suiteFactory = function(description) { 588 | var suite = new j$.Suite({ 589 | env: self, 590 | id: getNextSuiteId(), 591 | description: description, 592 | parentSuite: currentSuite, 593 | queueRunner: queueRunnerFactory, 594 | onStart: suiteStarted, 595 | resultCallback: function(attrs) { 596 | reporter.suiteDone(attrs); 597 | } 598 | }); 599 | 600 | runnableLookupTable[suite.id] = suite; 601 | return suite; 602 | }; 603 | 604 | this.describe = function(description, specDefinitions) { 605 | var suite = suiteFactory(description); 606 | 607 | var parentSuite = currentSuite; 608 | parentSuite.addChild(suite); 609 | currentSuite = suite; 610 | 611 | var declarationError = null; 612 | try { 613 | specDefinitions.call(suite); 614 | } catch (e) { 615 | declarationError = e; 616 | } 617 | 618 | if (declarationError) { 619 | this.it("encountered a declaration exception", function() { 620 | throw declarationError; 621 | }); 622 | } 623 | 624 | currentSuite = parentSuite; 625 | 626 | return suite; 627 | }; 628 | 629 | this.xdescribe = function(description, specDefinitions) { 630 | var suite = this.describe(description, specDefinitions); 631 | suite.disable(); 632 | return suite; 633 | }; 634 | 635 | var specFactory = function(description, fn, suite) { 636 | totalSpecsDefined++; 637 | 638 | var spec = new j$.Spec({ 639 | id: getNextSpecId(), 640 | beforeFns: beforeFns(suite), 641 | afterFns: afterFns(suite), 642 | expectationFactory: expectationFactory, 643 | exceptionFormatter: exceptionFormatter, 644 | resultCallback: specResultCallback, 645 | getSpecName: function(spec) { 646 | return getSpecName(spec, suite); 647 | }, 648 | onStart: specStarted, 649 | description: description, 650 | expectationResultFactory: expectationResultFactory, 651 | queueRunnerFactory: queueRunnerFactory, 652 | fn: fn, 653 | timer: {setTimeout: realSetTimeout, clearTimeout: realClearTimeout} 654 | }); 655 | 656 | runnableLookupTable[spec.id] = spec; 657 | 658 | if (!self.specFilter(spec)) { 659 | spec.disable(); 660 | } 661 | 662 | return spec; 663 | 664 | function removeAllSpies() { 665 | for (var i = 0; i < spies.length; i++) { 666 | var spyEntry = spies[i]; 667 | spyEntry.baseObj[spyEntry.methodName] = spyEntry.originalValue; 668 | } 669 | spies = []; 670 | } 671 | 672 | function specResultCallback(result) { 673 | removeAllSpies(); 674 | j$.Expectation.resetMatchers(); 675 | customEqualityTesters = []; 676 | currentSpec = null; 677 | reporter.specDone(result); 678 | } 679 | }; 680 | 681 | var suiteStarted = function(suite) { 682 | reporter.suiteStarted(suite.result); 683 | }; 684 | 685 | this.it = function(description, fn) { 686 | var spec = specFactory(description, fn, currentSuite); 687 | currentSuite.addChild(spec); 688 | return spec; 689 | }; 690 | 691 | this.xit = function(description, fn) { 692 | var spec = this.it(description, fn); 693 | spec.pend(); 694 | return spec; 695 | }; 696 | 697 | this.expect = function(actual) { 698 | return currentSpec.expect(actual); 699 | }; 700 | 701 | this.beforeEach = function(beforeEachFunction) { 702 | currentSuite.beforeEach(beforeEachFunction); 703 | }; 704 | 705 | this.afterEach = function(afterEachFunction) { 706 | currentSuite.afterEach(afterEachFunction); 707 | }; 708 | 709 | this.pending = function() { 710 | throw j$.Spec.pendingSpecExceptionMessage; 711 | }; 712 | } 713 | 714 | return Env; 715 | }; 716 | 717 | getJasmineRequireObj().JsApiReporter = function() { 718 | 719 | var noopTimer = { 720 | start: function(){}, 721 | elapsed: function(){ return 0; } 722 | }; 723 | 724 | function JsApiReporter(options) { 725 | var timer = options.timer || noopTimer, 726 | status = "loaded"; 727 | 728 | this.started = false; 729 | this.finished = false; 730 | 731 | this.jasmineStarted = function() { 732 | this.started = true; 733 | status = 'started'; 734 | timer.start(); 735 | }; 736 | 737 | var executionTime; 738 | 739 | this.jasmineDone = function() { 740 | this.finished = true; 741 | executionTime = timer.elapsed(); 742 | status = 'done'; 743 | }; 744 | 745 | this.status = function() { 746 | return status; 747 | }; 748 | 749 | var suites = {}; 750 | 751 | this.suiteStarted = function(result) { 752 | storeSuite(result); 753 | }; 754 | 755 | this.suiteDone = function(result) { 756 | storeSuite(result); 757 | }; 758 | 759 | function storeSuite(result) { 760 | suites[result.id] = result; 761 | } 762 | 763 | this.suites = function() { 764 | return suites; 765 | }; 766 | 767 | var specs = []; 768 | this.specStarted = function(result) { }; 769 | 770 | this.specDone = function(result) { 771 | specs.push(result); 772 | }; 773 | 774 | this.specResults = function(index, length) { 775 | return specs.slice(index, index + length); 776 | }; 777 | 778 | this.specs = function() { 779 | return specs; 780 | }; 781 | 782 | this.executionTime = function() { 783 | return executionTime; 784 | }; 785 | 786 | } 787 | 788 | return JsApiReporter; 789 | }; 790 | 791 | getJasmineRequireObj().Any = function() { 792 | 793 | function Any(expectedObject) { 794 | this.expectedObject = expectedObject; 795 | } 796 | 797 | Any.prototype.jasmineMatches = function(other) { 798 | if (this.expectedObject == String) { 799 | return typeof other == 'string' || other instanceof String; 800 | } 801 | 802 | if (this.expectedObject == Number) { 803 | return typeof other == 'number' || other instanceof Number; 804 | } 805 | 806 | if (this.expectedObject == Function) { 807 | return typeof other == 'function' || other instanceof Function; 808 | } 809 | 810 | if (this.expectedObject == Object) { 811 | return typeof other == 'object'; 812 | } 813 | 814 | if (this.expectedObject == Boolean) { 815 | return typeof other == 'boolean'; 816 | } 817 | 818 | return other instanceof this.expectedObject; 819 | }; 820 | 821 | Any.prototype.jasmineToString = function() { 822 | return ''; 823 | }; 824 | 825 | return Any; 826 | }; 827 | 828 | getJasmineRequireObj().CallTracker = function() { 829 | 830 | function CallTracker() { 831 | var calls = []; 832 | 833 | this.track = function(context) { 834 | calls.push(context); 835 | }; 836 | 837 | this.any = function() { 838 | return !!calls.length; 839 | }; 840 | 841 | this.count = function() { 842 | return calls.length; 843 | }; 844 | 845 | this.argsFor = function(index) { 846 | var call = calls[index]; 847 | return call ? call.args : []; 848 | }; 849 | 850 | this.all = function() { 851 | return calls; 852 | }; 853 | 854 | this.allArgs = function() { 855 | var callArgs = []; 856 | for(var i = 0; i < calls.length; i++){ 857 | callArgs.push(calls[i].args); 858 | } 859 | 860 | return callArgs; 861 | }; 862 | 863 | this.first = function() { 864 | return calls[0]; 865 | }; 866 | 867 | this.mostRecent = function() { 868 | return calls[calls.length - 1]; 869 | }; 870 | 871 | this.reset = function() { 872 | calls = []; 873 | }; 874 | } 875 | 876 | return CallTracker; 877 | }; 878 | 879 | getJasmineRequireObj().Clock = function() { 880 | function Clock(global, delayedFunctionScheduler) { 881 | var self = this, 882 | realTimingFunctions = { 883 | setTimeout: global.setTimeout, 884 | clearTimeout: global.clearTimeout, 885 | setInterval: global.setInterval, 886 | clearInterval: global.clearInterval 887 | }, 888 | fakeTimingFunctions = { 889 | setTimeout: setTimeout, 890 | clearTimeout: clearTimeout, 891 | setInterval: setInterval, 892 | clearInterval: clearInterval 893 | }, 894 | installed = false, 895 | timer; 896 | 897 | self.install = function() { 898 | replace(global, fakeTimingFunctions); 899 | timer = fakeTimingFunctions; 900 | installed = true; 901 | }; 902 | 903 | self.uninstall = function() { 904 | delayedFunctionScheduler.reset(); 905 | replace(global, realTimingFunctions); 906 | timer = realTimingFunctions; 907 | installed = false; 908 | }; 909 | 910 | self.setTimeout = function(fn, delay, params) { 911 | if (legacyIE()) { 912 | if (arguments.length > 2) { 913 | throw new Error("IE < 9 cannot support extra params to setTimeout without a polyfill"); 914 | } 915 | return timer.setTimeout(fn, delay); 916 | } 917 | return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]); 918 | }; 919 | 920 | self.setInterval = function(fn, delay, params) { 921 | if (legacyIE()) { 922 | if (arguments.length > 2) { 923 | throw new Error("IE < 9 cannot support extra params to setInterval without a polyfill"); 924 | } 925 | return timer.setInterval(fn, delay); 926 | } 927 | return Function.prototype.apply.apply(timer.setInterval, [global, arguments]); 928 | }; 929 | 930 | self.clearTimeout = function(id) { 931 | return Function.prototype.call.apply(timer.clearTimeout, [global, id]); 932 | }; 933 | 934 | self.clearInterval = function(id) { 935 | return Function.prototype.call.apply(timer.clearInterval, [global, id]); 936 | }; 937 | 938 | self.tick = function(millis) { 939 | if (installed) { 940 | delayedFunctionScheduler.tick(millis); 941 | } else { 942 | throw new Error("Mock clock is not installed, use jasmine.clock().install()"); 943 | } 944 | }; 945 | 946 | return self; 947 | 948 | function legacyIE() { 949 | //if these methods are polyfilled, apply will be present 950 | return !(realTimingFunctions.setTimeout || realTimingFunctions.setInterval).apply; 951 | } 952 | 953 | function replace(dest, source) { 954 | for (var prop in source) { 955 | dest[prop] = source[prop]; 956 | } 957 | } 958 | 959 | function setTimeout(fn, delay) { 960 | return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2)); 961 | } 962 | 963 | function clearTimeout(id) { 964 | return delayedFunctionScheduler.removeFunctionWithId(id); 965 | } 966 | 967 | function setInterval(fn, interval) { 968 | return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true); 969 | } 970 | 971 | function clearInterval(id) { 972 | return delayedFunctionScheduler.removeFunctionWithId(id); 973 | } 974 | 975 | function argSlice(argsObj, n) { 976 | return Array.prototype.slice.call(argsObj, 2); 977 | } 978 | } 979 | 980 | return Clock; 981 | }; 982 | 983 | getJasmineRequireObj().DelayedFunctionScheduler = function() { 984 | function DelayedFunctionScheduler() { 985 | var self = this; 986 | var scheduledLookup = []; 987 | var scheduledFunctions = {}; 988 | var currentTime = 0; 989 | var delayedFnCount = 0; 990 | 991 | self.tick = function(millis) { 992 | millis = millis || 0; 993 | var endTime = currentTime + millis; 994 | 995 | runScheduledFunctions(endTime); 996 | currentTime = endTime; 997 | }; 998 | 999 | self.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) { 1000 | var f; 1001 | if (typeof(funcToCall) === 'string') { 1002 | /* jshint evil: true */ 1003 | f = function() { return eval(funcToCall); }; 1004 | /* jshint evil: false */ 1005 | } else { 1006 | f = funcToCall; 1007 | } 1008 | 1009 | millis = millis || 0; 1010 | timeoutKey = timeoutKey || ++delayedFnCount; 1011 | runAtMillis = runAtMillis || (currentTime + millis); 1012 | 1013 | var funcToSchedule = { 1014 | runAtMillis: runAtMillis, 1015 | funcToCall: f, 1016 | recurring: recurring, 1017 | params: params, 1018 | timeoutKey: timeoutKey, 1019 | millis: millis 1020 | }; 1021 | 1022 | if (runAtMillis in scheduledFunctions) { 1023 | scheduledFunctions[runAtMillis].push(funcToSchedule); 1024 | } else { 1025 | scheduledFunctions[runAtMillis] = [funcToSchedule]; 1026 | scheduledLookup.push(runAtMillis); 1027 | scheduledLookup.sort(function (a, b) { 1028 | return a - b; 1029 | }); 1030 | } 1031 | 1032 | return timeoutKey; 1033 | }; 1034 | 1035 | self.removeFunctionWithId = function(timeoutKey) { 1036 | for (var runAtMillis in scheduledFunctions) { 1037 | var funcs = scheduledFunctions[runAtMillis]; 1038 | var i = indexOfFirstToPass(funcs, function (func) { 1039 | return func.timeoutKey === timeoutKey; 1040 | }); 1041 | 1042 | if (i > -1) { 1043 | if (funcs.length === 1) { 1044 | delete scheduledFunctions[runAtMillis]; 1045 | deleteFromLookup(runAtMillis); 1046 | } else { 1047 | funcs.splice(i, 1); 1048 | } 1049 | 1050 | // intervals get rescheduled when executed, so there's never more 1051 | // than a single scheduled function with a given timeoutKey 1052 | break; 1053 | } 1054 | } 1055 | }; 1056 | 1057 | self.reset = function() { 1058 | currentTime = 0; 1059 | scheduledLookup = []; 1060 | scheduledFunctions = {}; 1061 | delayedFnCount = 0; 1062 | }; 1063 | 1064 | return self; 1065 | 1066 | function indexOfFirstToPass(array, testFn) { 1067 | var index = -1; 1068 | 1069 | for (var i = 0; i < array.length; ++i) { 1070 | if (testFn(array[i])) { 1071 | index = i; 1072 | break; 1073 | } 1074 | } 1075 | 1076 | return index; 1077 | } 1078 | 1079 | function deleteFromLookup(key) { 1080 | var value = Number(key); 1081 | var i = indexOfFirstToPass(scheduledLookup, function (millis) { 1082 | return millis === value; 1083 | }); 1084 | 1085 | if (i > -1) { 1086 | scheduledLookup.splice(i, 1); 1087 | } 1088 | } 1089 | 1090 | function reschedule(scheduledFn) { 1091 | self.scheduleFunction(scheduledFn.funcToCall, 1092 | scheduledFn.millis, 1093 | scheduledFn.params, 1094 | true, 1095 | scheduledFn.timeoutKey, 1096 | scheduledFn.runAtMillis + scheduledFn.millis); 1097 | } 1098 | 1099 | function runScheduledFunctions(endTime) { 1100 | if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) { 1101 | return; 1102 | } 1103 | 1104 | do { 1105 | currentTime = scheduledLookup.shift(); 1106 | 1107 | var funcsToRun = scheduledFunctions[currentTime]; 1108 | delete scheduledFunctions[currentTime]; 1109 | 1110 | for (var i = 0; i < funcsToRun.length; ++i) { 1111 | var funcToRun = funcsToRun[i]; 1112 | funcToRun.funcToCall.apply(null, funcToRun.params || []); 1113 | 1114 | if (funcToRun.recurring) { 1115 | reschedule(funcToRun); 1116 | } 1117 | } 1118 | } while (scheduledLookup.length > 0 && 1119 | // checking first if we're out of time prevents setTimeout(0) 1120 | // scheduled in a funcToRun from forcing an extra iteration 1121 | currentTime !== endTime && 1122 | scheduledLookup[0] <= endTime); 1123 | } 1124 | } 1125 | 1126 | return DelayedFunctionScheduler; 1127 | }; 1128 | 1129 | getJasmineRequireObj().ExceptionFormatter = function() { 1130 | function ExceptionFormatter() { 1131 | this.message = function(error) { 1132 | var message = error.name + 1133 | ': ' + 1134 | error.message; 1135 | 1136 | if (error.fileName || error.sourceURL) { 1137 | message += " in " + (error.fileName || error.sourceURL); 1138 | } 1139 | 1140 | if (error.line || error.lineNumber) { 1141 | message += " (line " + (error.line || error.lineNumber) + ")"; 1142 | } 1143 | 1144 | return message; 1145 | }; 1146 | 1147 | this.stack = function(error) { 1148 | return error ? error.stack : null; 1149 | }; 1150 | } 1151 | 1152 | return ExceptionFormatter; 1153 | }; 1154 | 1155 | getJasmineRequireObj().Expectation = function() { 1156 | 1157 | var matchers = {}; 1158 | 1159 | function Expectation(options) { 1160 | this.util = options.util || { buildFailureMessage: function() {} }; 1161 | this.customEqualityTesters = options.customEqualityTesters || []; 1162 | this.actual = options.actual; 1163 | this.addExpectationResult = options.addExpectationResult || function(){}; 1164 | this.isNot = options.isNot; 1165 | 1166 | for (var matcherName in matchers) { 1167 | this[matcherName] = matchers[matcherName]; 1168 | } 1169 | } 1170 | 1171 | Expectation.prototype.wrapCompare = function(name, matcherFactory) { 1172 | return function() { 1173 | var args = Array.prototype.slice.call(arguments, 0), 1174 | expected = args.slice(0), 1175 | message = ""; 1176 | 1177 | args.unshift(this.actual); 1178 | 1179 | var matcher = matcherFactory(this.util, this.customEqualityTesters), 1180 | matcherCompare = matcher.compare; 1181 | 1182 | function defaultNegativeCompare() { 1183 | var result = matcher.compare.apply(null, args); 1184 | result.pass = !result.pass; 1185 | return result; 1186 | } 1187 | 1188 | if (this.isNot) { 1189 | matcherCompare = matcher.negativeCompare || defaultNegativeCompare; 1190 | } 1191 | 1192 | var result = matcherCompare.apply(null, args); 1193 | 1194 | if (!result.pass) { 1195 | if (!result.message) { 1196 | args.unshift(this.isNot); 1197 | args.unshift(name); 1198 | message = this.util.buildFailureMessage.apply(null, args); 1199 | } else { 1200 | message = result.message; 1201 | } 1202 | } 1203 | 1204 | if (expected.length == 1) { 1205 | expected = expected[0]; 1206 | } 1207 | 1208 | // TODO: how many of these params are needed? 1209 | this.addExpectationResult( 1210 | result.pass, 1211 | { 1212 | matcherName: name, 1213 | passed: result.pass, 1214 | message: message, 1215 | actual: this.actual, 1216 | expected: expected // TODO: this may need to be arrayified/sliced 1217 | } 1218 | ); 1219 | }; 1220 | }; 1221 | 1222 | Expectation.addCoreMatchers = function(matchers) { 1223 | var prototype = Expectation.prototype; 1224 | for (var matcherName in matchers) { 1225 | var matcher = matchers[matcherName]; 1226 | prototype[matcherName] = prototype.wrapCompare(matcherName, matcher); 1227 | } 1228 | }; 1229 | 1230 | Expectation.addMatchers = function(matchersToAdd) { 1231 | for (var name in matchersToAdd) { 1232 | var matcher = matchersToAdd[name]; 1233 | matchers[name] = Expectation.prototype.wrapCompare(name, matcher); 1234 | } 1235 | }; 1236 | 1237 | Expectation.resetMatchers = function() { 1238 | for (var name in matchers) { 1239 | delete matchers[name]; 1240 | } 1241 | }; 1242 | 1243 | Expectation.Factory = function(options) { 1244 | options = options || {}; 1245 | 1246 | var expect = new Expectation(options); 1247 | 1248 | // TODO: this would be nice as its own Object - NegativeExpectation 1249 | // TODO: copy instead of mutate options 1250 | options.isNot = true; 1251 | expect.not = new Expectation(options); 1252 | 1253 | return expect; 1254 | }; 1255 | 1256 | return Expectation; 1257 | }; 1258 | 1259 | //TODO: expectation result may make more sense as a presentation of an expectation. 1260 | getJasmineRequireObj().buildExpectationResult = function() { 1261 | function buildExpectationResult(options) { 1262 | var messageFormatter = options.messageFormatter || function() {}, 1263 | stackFormatter = options.stackFormatter || function() {}; 1264 | 1265 | return { 1266 | matcherName: options.matcherName, 1267 | expected: options.expected, 1268 | actual: options.actual, 1269 | message: message(), 1270 | stack: stack(), 1271 | passed: options.passed 1272 | }; 1273 | 1274 | function message() { 1275 | if (options.passed) { 1276 | return "Passed."; 1277 | } else if (options.message) { 1278 | return options.message; 1279 | } else if (options.error) { 1280 | return messageFormatter(options.error); 1281 | } 1282 | return ""; 1283 | } 1284 | 1285 | function stack() { 1286 | if (options.passed) { 1287 | return ""; 1288 | } 1289 | 1290 | var error = options.error; 1291 | if (!error) { 1292 | try { 1293 | throw new Error(message()); 1294 | } catch (e) { 1295 | error = e; 1296 | } 1297 | } 1298 | return stackFormatter(error); 1299 | } 1300 | } 1301 | 1302 | return buildExpectationResult; 1303 | }; 1304 | 1305 | getJasmineRequireObj().ObjectContaining = function(j$) { 1306 | 1307 | function ObjectContaining(sample) { 1308 | this.sample = sample; 1309 | } 1310 | 1311 | ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) { 1312 | if (typeof(this.sample) !== "object") { throw new Error("You must provide an object to objectContaining, not '"+this.sample+"'."); } 1313 | 1314 | mismatchKeys = mismatchKeys || []; 1315 | mismatchValues = mismatchValues || []; 1316 | 1317 | var hasKey = function(obj, keyName) { 1318 | return obj !== null && !j$.util.isUndefined(obj[keyName]); 1319 | }; 1320 | 1321 | for (var property in this.sample) { 1322 | if (!hasKey(other, property) && hasKey(this.sample, property)) { 1323 | mismatchKeys.push("expected has key '" + property + "', but missing from actual."); 1324 | } 1325 | else if (!j$.matchersUtil.equals(this.sample[property], other[property])) { 1326 | mismatchValues.push("'" + property + "' was '" + (other[property] ? j$.util.htmlEscape(other[property].toString()) : other[property]) + "' in actual, but was '" + (this.sample[property] ? j$.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in expected."); 1327 | } 1328 | } 1329 | 1330 | return (mismatchKeys.length === 0 && mismatchValues.length === 0); 1331 | }; 1332 | 1333 | ObjectContaining.prototype.jasmineToString = function() { 1334 | return ""; 1335 | }; 1336 | 1337 | return ObjectContaining; 1338 | }; 1339 | 1340 | getJasmineRequireObj().pp = function(j$) { 1341 | 1342 | function PrettyPrinter() { 1343 | this.ppNestLevel_ = 0; 1344 | } 1345 | 1346 | PrettyPrinter.prototype.format = function(value) { 1347 | this.ppNestLevel_++; 1348 | try { 1349 | if (j$.util.isUndefined(value)) { 1350 | this.emitScalar('undefined'); 1351 | } else if (value === null) { 1352 | this.emitScalar('null'); 1353 | } else if (value === j$.getGlobal()) { 1354 | this.emitScalar(''); 1355 | } else if (value.jasmineToString) { 1356 | this.emitScalar(value.jasmineToString()); 1357 | } else if (typeof value === 'string') { 1358 | this.emitString(value); 1359 | } else if (j$.isSpy(value)) { 1360 | this.emitScalar("spy on " + value.and.identity()); 1361 | } else if (value instanceof RegExp) { 1362 | this.emitScalar(value.toString()); 1363 | } else if (typeof value === 'function') { 1364 | this.emitScalar('Function'); 1365 | } else if (typeof value.nodeType === 'number') { 1366 | this.emitScalar('HTMLNode'); 1367 | } else if (value instanceof Date) { 1368 | this.emitScalar('Date(' + value + ')'); 1369 | } else if (value.__Jasmine_been_here_before__) { 1370 | this.emitScalar(''); 1371 | } else if (j$.isArray_(value) || j$.isA_('Object', value)) { 1372 | value.__Jasmine_been_here_before__ = true; 1373 | if (j$.isArray_(value)) { 1374 | this.emitArray(value); 1375 | } else { 1376 | this.emitObject(value); 1377 | } 1378 | delete value.__Jasmine_been_here_before__; 1379 | } else { 1380 | this.emitScalar(value.toString()); 1381 | } 1382 | } finally { 1383 | this.ppNestLevel_--; 1384 | } 1385 | }; 1386 | 1387 | PrettyPrinter.prototype.iterateObject = function(obj, fn) { 1388 | for (var property in obj) { 1389 | if (!obj.hasOwnProperty(property)) { continue; } 1390 | if (property == '__Jasmine_been_here_before__') { continue; } 1391 | fn(property, obj.__lookupGetter__ ? (!j$.util.isUndefined(obj.__lookupGetter__(property)) && 1392 | obj.__lookupGetter__(property) !== null) : false); 1393 | } 1394 | }; 1395 | 1396 | PrettyPrinter.prototype.emitArray = j$.unimplementedMethod_; 1397 | PrettyPrinter.prototype.emitObject = j$.unimplementedMethod_; 1398 | PrettyPrinter.prototype.emitScalar = j$.unimplementedMethod_; 1399 | PrettyPrinter.prototype.emitString = j$.unimplementedMethod_; 1400 | 1401 | function StringPrettyPrinter() { 1402 | PrettyPrinter.call(this); 1403 | 1404 | this.string = ''; 1405 | } 1406 | 1407 | j$.util.inherit(StringPrettyPrinter, PrettyPrinter); 1408 | 1409 | StringPrettyPrinter.prototype.emitScalar = function(value) { 1410 | this.append(value); 1411 | }; 1412 | 1413 | StringPrettyPrinter.prototype.emitString = function(value) { 1414 | this.append("'" + value + "'"); 1415 | }; 1416 | 1417 | StringPrettyPrinter.prototype.emitArray = function(array) { 1418 | if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { 1419 | this.append("Array"); 1420 | return; 1421 | } 1422 | 1423 | this.append('[ '); 1424 | for (var i = 0; i < array.length; i++) { 1425 | if (i > 0) { 1426 | this.append(', '); 1427 | } 1428 | this.format(array[i]); 1429 | } 1430 | this.append(' ]'); 1431 | }; 1432 | 1433 | StringPrettyPrinter.prototype.emitObject = function(obj) { 1434 | if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { 1435 | this.append("Object"); 1436 | return; 1437 | } 1438 | 1439 | var self = this; 1440 | this.append('{ '); 1441 | var first = true; 1442 | 1443 | this.iterateObject(obj, function(property, isGetter) { 1444 | if (first) { 1445 | first = false; 1446 | } else { 1447 | self.append(', '); 1448 | } 1449 | 1450 | self.append(property); 1451 | self.append(' : '); 1452 | if (isGetter) { 1453 | self.append(''); 1454 | } else { 1455 | self.format(obj[property]); 1456 | } 1457 | }); 1458 | 1459 | this.append(' }'); 1460 | }; 1461 | 1462 | StringPrettyPrinter.prototype.append = function(value) { 1463 | this.string += value; 1464 | }; 1465 | 1466 | return function(value) { 1467 | var stringPrettyPrinter = new StringPrettyPrinter(); 1468 | stringPrettyPrinter.format(value); 1469 | return stringPrettyPrinter.string; 1470 | }; 1471 | }; 1472 | 1473 | getJasmineRequireObj().QueueRunner = function() { 1474 | 1475 | function QueueRunner(attrs) { 1476 | this.fns = attrs.fns || []; 1477 | this.onComplete = attrs.onComplete || function() {}; 1478 | this.clearStack = attrs.clearStack || function(fn) {fn();}; 1479 | this.onException = attrs.onException || function() {}; 1480 | this.catchException = attrs.catchException || function() { return true; }; 1481 | this.userContext = {}; 1482 | } 1483 | 1484 | QueueRunner.prototype.execute = function() { 1485 | this.run(this.fns, 0); 1486 | }; 1487 | 1488 | QueueRunner.prototype.run = function(fns, recursiveIndex) { 1489 | var length = fns.length, 1490 | self = this, 1491 | iterativeIndex; 1492 | 1493 | for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) { 1494 | var fn = fns[iterativeIndex]; 1495 | if (fn.length > 0) { 1496 | return attemptAsync(fn); 1497 | } else { 1498 | attemptSync(fn); 1499 | } 1500 | } 1501 | 1502 | var runnerDone = iterativeIndex >= length; 1503 | 1504 | if (runnerDone) { 1505 | this.clearStack(this.onComplete); 1506 | } 1507 | 1508 | function attemptSync(fn) { 1509 | try { 1510 | fn.call(self.userContext); 1511 | } catch (e) { 1512 | handleException(e); 1513 | } 1514 | } 1515 | 1516 | function attemptAsync(fn) { 1517 | var next = function () { self.run(fns, iterativeIndex + 1); }; 1518 | 1519 | try { 1520 | fn.call(self.userContext, next); 1521 | } catch (e) { 1522 | handleException(e); 1523 | next(); 1524 | } 1525 | } 1526 | 1527 | function handleException(e) { 1528 | self.onException(e); 1529 | if (!self.catchException(e)) { 1530 | //TODO: set a var when we catch an exception and 1531 | //use a finally block to close the loop in a nice way.. 1532 | throw e; 1533 | } 1534 | } 1535 | }; 1536 | 1537 | return QueueRunner; 1538 | }; 1539 | 1540 | getJasmineRequireObj().ReportDispatcher = function() { 1541 | function ReportDispatcher(methods) { 1542 | 1543 | var dispatchedMethods = methods || []; 1544 | 1545 | for (var i = 0; i < dispatchedMethods.length; i++) { 1546 | var method = dispatchedMethods[i]; 1547 | this[method] = (function(m) { 1548 | return function() { 1549 | dispatch(m, arguments); 1550 | }; 1551 | }(method)); 1552 | } 1553 | 1554 | var reporters = []; 1555 | 1556 | this.addReporter = function(reporter) { 1557 | reporters.push(reporter); 1558 | }; 1559 | 1560 | return this; 1561 | 1562 | function dispatch(method, args) { 1563 | for (var i = 0; i < reporters.length; i++) { 1564 | var reporter = reporters[i]; 1565 | if (reporter[method]) { 1566 | reporter[method].apply(reporter, args); 1567 | } 1568 | } 1569 | } 1570 | } 1571 | 1572 | return ReportDispatcher; 1573 | }; 1574 | 1575 | 1576 | getJasmineRequireObj().SpyStrategy = function() { 1577 | 1578 | function SpyStrategy(options) { 1579 | options = options || {}; 1580 | 1581 | var identity = options.name || "unknown", 1582 | originalFn = options.fn || function() {}, 1583 | getSpy = options.getSpy || function() {}, 1584 | plan = function() {}; 1585 | 1586 | this.identity = function() { 1587 | return identity; 1588 | }; 1589 | 1590 | this.exec = function() { 1591 | return plan.apply(this, arguments); 1592 | }; 1593 | 1594 | this.callThrough = function() { 1595 | plan = originalFn; 1596 | return getSpy(); 1597 | }; 1598 | 1599 | this.returnValue = function(value) { 1600 | plan = function() { 1601 | return value; 1602 | }; 1603 | return getSpy(); 1604 | }; 1605 | 1606 | this.throwError = function(something) { 1607 | var error = (something instanceof Error) ? something : new Error(something); 1608 | plan = function() { 1609 | throw error; 1610 | }; 1611 | return getSpy(); 1612 | }; 1613 | 1614 | this.callFake = function(fn) { 1615 | plan = fn; 1616 | return getSpy(); 1617 | }; 1618 | 1619 | this.stub = function(fn) { 1620 | plan = function() {}; 1621 | return getSpy(); 1622 | }; 1623 | } 1624 | 1625 | return SpyStrategy; 1626 | }; 1627 | 1628 | getJasmineRequireObj().Suite = function() { 1629 | function Suite(attrs) { 1630 | this.env = attrs.env; 1631 | this.id = attrs.id; 1632 | this.parentSuite = attrs.parentSuite; 1633 | this.description = attrs.description; 1634 | this.onStart = attrs.onStart || function() {}; 1635 | this.resultCallback = attrs.resultCallback || function() {}; 1636 | this.clearStack = attrs.clearStack || function(fn) {fn();}; 1637 | 1638 | this.beforeFns = []; 1639 | this.afterFns = []; 1640 | this.queueRunner = attrs.queueRunner || function() {}; 1641 | this.disabled = false; 1642 | 1643 | this.children = []; 1644 | 1645 | this.result = { 1646 | id: this.id, 1647 | status: this.disabled ? 'disabled' : '', 1648 | description: this.description, 1649 | fullName: this.getFullName() 1650 | }; 1651 | } 1652 | 1653 | Suite.prototype.getFullName = function() { 1654 | var fullName = this.description; 1655 | for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { 1656 | if (parentSuite.parentSuite) { 1657 | fullName = parentSuite.description + ' ' + fullName; 1658 | } 1659 | } 1660 | return fullName; 1661 | }; 1662 | 1663 | Suite.prototype.disable = function() { 1664 | this.disabled = true; 1665 | }; 1666 | 1667 | Suite.prototype.beforeEach = function(fn) { 1668 | this.beforeFns.unshift(fn); 1669 | }; 1670 | 1671 | Suite.prototype.afterEach = function(fn) { 1672 | this.afterFns.unshift(fn); 1673 | }; 1674 | 1675 | Suite.prototype.addChild = function(child) { 1676 | this.children.push(child); 1677 | }; 1678 | 1679 | Suite.prototype.execute = function(onComplete) { 1680 | var self = this; 1681 | if (this.disabled) { 1682 | complete(); 1683 | return; 1684 | } 1685 | 1686 | var allFns = []; 1687 | 1688 | for (var i = 0; i < this.children.length; i++) { 1689 | allFns.push(wrapChildAsAsync(this.children[i])); 1690 | } 1691 | 1692 | this.onStart(this); 1693 | 1694 | this.queueRunner({ 1695 | fns: allFns, 1696 | onComplete: complete 1697 | }); 1698 | 1699 | function complete() { 1700 | self.resultCallback(self.result); 1701 | 1702 | if (onComplete) { 1703 | onComplete(); 1704 | } 1705 | } 1706 | 1707 | function wrapChildAsAsync(child) { 1708 | return function(done) { child.execute(done); }; 1709 | } 1710 | }; 1711 | 1712 | return Suite; 1713 | }; 1714 | 1715 | if (typeof window == void 0 && typeof exports == "object") { 1716 | exports.Suite = jasmineRequire.Suite; 1717 | } 1718 | 1719 | getJasmineRequireObj().Timer = function() { 1720 | function Timer(options) { 1721 | options = options || {}; 1722 | 1723 | var now = options.now || function() { return new Date().getTime(); }, 1724 | startTime; 1725 | 1726 | this.start = function() { 1727 | startTime = now(); 1728 | }; 1729 | 1730 | this.elapsed = function() { 1731 | return now() - startTime; 1732 | }; 1733 | } 1734 | 1735 | return Timer; 1736 | }; 1737 | 1738 | getJasmineRequireObj().matchersUtil = function(j$) { 1739 | // TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter? 1740 | 1741 | return { 1742 | equals: function(a, b, customTesters) { 1743 | customTesters = customTesters || []; 1744 | 1745 | return eq(a, b, [], [], customTesters); 1746 | }, 1747 | 1748 | contains: function(haystack, needle, customTesters) { 1749 | customTesters = customTesters || []; 1750 | 1751 | if (Object.prototype.toString.apply(haystack) === "[object Array]") { 1752 | for (var i = 0; i < haystack.length; i++) { 1753 | if (eq(haystack[i], needle, [], [], customTesters)) { 1754 | return true; 1755 | } 1756 | } 1757 | return false; 1758 | } 1759 | return haystack.indexOf(needle) >= 0; 1760 | }, 1761 | 1762 | buildFailureMessage: function() { 1763 | var args = Array.prototype.slice.call(arguments, 0), 1764 | matcherName = args[0], 1765 | isNot = args[1], 1766 | actual = args[2], 1767 | expected = args.slice(3), 1768 | englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); 1769 | 1770 | var message = "Expected " + 1771 | j$.pp(actual) + 1772 | (isNot ? " not " : " ") + 1773 | englishyPredicate; 1774 | 1775 | if (expected.length > 0) { 1776 | for (var i = 0; i < expected.length; i++) { 1777 | if (i > 0) { 1778 | message += ","; 1779 | } 1780 | message += " " + j$.pp(expected[i]); 1781 | } 1782 | } 1783 | 1784 | return message + "."; 1785 | } 1786 | }; 1787 | 1788 | // Equality function lovingly adapted from isEqual in 1789 | // [Underscore](http://underscorejs.org) 1790 | function eq(a, b, aStack, bStack, customTesters) { 1791 | var result = true; 1792 | 1793 | for (var i = 0; i < customTesters.length; i++) { 1794 | var customTesterResult = customTesters[i](a, b); 1795 | if (!j$.util.isUndefined(customTesterResult)) { 1796 | return customTesterResult; 1797 | } 1798 | } 1799 | 1800 | if (a instanceof j$.Any) { 1801 | result = a.jasmineMatches(b); 1802 | if (result) { 1803 | return true; 1804 | } 1805 | } 1806 | 1807 | if (b instanceof j$.Any) { 1808 | result = b.jasmineMatches(a); 1809 | if (result) { 1810 | return true; 1811 | } 1812 | } 1813 | 1814 | if (b instanceof j$.ObjectContaining) { 1815 | result = b.jasmineMatches(a); 1816 | if (result) { 1817 | return true; 1818 | } 1819 | } 1820 | 1821 | if (a instanceof Error && b instanceof Error) { 1822 | return a.message == b.message; 1823 | } 1824 | 1825 | // Identical objects are equal. `0 === -0`, but they aren't identical. 1826 | // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). 1827 | if (a === b) { return a !== 0 || 1 / a == 1 / b; } 1828 | // A strict comparison is necessary because `null == undefined`. 1829 | if (a === null || b === null) { return a === b; } 1830 | var className = Object.prototype.toString.call(a); 1831 | if (className != Object.prototype.toString.call(b)) { return false; } 1832 | switch (className) { 1833 | // Strings, numbers, dates, and booleans are compared by value. 1834 | case '[object String]': 1835 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is 1836 | // equivalent to `new String("5")`. 1837 | return a == String(b); 1838 | case '[object Number]': 1839 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for 1840 | // other numeric values. 1841 | return a != +a ? b != +b : (a === 0 ? 1 / a == 1 / b : a == +b); 1842 | case '[object Date]': 1843 | case '[object Boolean]': 1844 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their 1845 | // millisecond representations. Note that invalid dates with millisecond representations 1846 | // of `NaN` are not equivalent. 1847 | return +a == +b; 1848 | // RegExps are compared by their source patterns and flags. 1849 | case '[object RegExp]': 1850 | return a.source == b.source && 1851 | a.global == b.global && 1852 | a.multiline == b.multiline && 1853 | a.ignoreCase == b.ignoreCase; 1854 | } 1855 | if (typeof a != 'object' || typeof b != 'object') { return false; } 1856 | // Assume equality for cyclic structures. The algorithm for detecting cyclic 1857 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. 1858 | var length = aStack.length; 1859 | while (length--) { 1860 | // Linear search. Performance is inversely proportional to the number of 1861 | // unique nested structures. 1862 | if (aStack[length] == a) { return bStack[length] == b; } 1863 | } 1864 | // Add the first object to the stack of traversed objects. 1865 | aStack.push(a); 1866 | bStack.push(b); 1867 | var size = 0; 1868 | // Recursively compare objects and arrays. 1869 | if (className == '[object Array]') { 1870 | // Compare array lengths to determine if a deep comparison is necessary. 1871 | size = a.length; 1872 | result = size == b.length; 1873 | if (result) { 1874 | // Deep compare the contents, ignoring non-numeric properties. 1875 | while (size--) { 1876 | if (!(result = eq(a[size], b[size], aStack, bStack, customTesters))) { break; } 1877 | } 1878 | } 1879 | } else { 1880 | // Objects with different constructors are not equivalent, but `Object`s 1881 | // from different frames are. 1882 | var aCtor = a.constructor, bCtor = b.constructor; 1883 | if (aCtor !== bCtor && !(isFunction(aCtor) && (aCtor instanceof aCtor) && 1884 | isFunction(bCtor) && (bCtor instanceof bCtor))) { 1885 | return false; 1886 | } 1887 | // Deep compare objects. 1888 | for (var key in a) { 1889 | if (has(a, key)) { 1890 | // Count the expected number of properties. 1891 | size++; 1892 | // Deep compare each member. 1893 | if (!(result = has(b, key) && eq(a[key], b[key], aStack, bStack, customTesters))) { break; } 1894 | } 1895 | } 1896 | // Ensure that both objects contain the same number of properties. 1897 | if (result) { 1898 | for (key in b) { 1899 | if (has(b, key) && !(size--)) { break; } 1900 | } 1901 | result = !size; 1902 | } 1903 | } 1904 | // Remove the first object from the stack of traversed objects. 1905 | aStack.pop(); 1906 | bStack.pop(); 1907 | 1908 | return result; 1909 | 1910 | function has(obj, key) { 1911 | return obj.hasOwnProperty(key); 1912 | } 1913 | 1914 | function isFunction(obj) { 1915 | return typeof obj === 'function'; 1916 | } 1917 | } 1918 | }; 1919 | 1920 | getJasmineRequireObj().toBe = function() { 1921 | function toBe() { 1922 | return { 1923 | compare: function(actual, expected) { 1924 | return { 1925 | pass: actual === expected 1926 | }; 1927 | } 1928 | }; 1929 | } 1930 | 1931 | return toBe; 1932 | }; 1933 | 1934 | getJasmineRequireObj().toBeCloseTo = function() { 1935 | 1936 | function toBeCloseTo() { 1937 | return { 1938 | compare: function(actual, expected, precision) { 1939 | if (precision !== 0) { 1940 | precision = precision || 2; 1941 | } 1942 | 1943 | return { 1944 | pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2) 1945 | }; 1946 | } 1947 | }; 1948 | } 1949 | 1950 | return toBeCloseTo; 1951 | }; 1952 | 1953 | getJasmineRequireObj().toBeDefined = function() { 1954 | function toBeDefined() { 1955 | return { 1956 | compare: function(actual) { 1957 | return { 1958 | pass: (void 0 !== actual) 1959 | }; 1960 | } 1961 | }; 1962 | } 1963 | 1964 | return toBeDefined; 1965 | }; 1966 | 1967 | getJasmineRequireObj().toBeFalsy = function() { 1968 | function toBeFalsy() { 1969 | return { 1970 | compare: function(actual) { 1971 | return { 1972 | pass: !!!actual 1973 | }; 1974 | } 1975 | }; 1976 | } 1977 | 1978 | return toBeFalsy; 1979 | }; 1980 | 1981 | getJasmineRequireObj().toBeGreaterThan = function() { 1982 | 1983 | function toBeGreaterThan() { 1984 | return { 1985 | compare: function(actual, expected) { 1986 | return { 1987 | pass: actual > expected 1988 | }; 1989 | } 1990 | }; 1991 | } 1992 | 1993 | return toBeGreaterThan; 1994 | }; 1995 | 1996 | 1997 | getJasmineRequireObj().toBeLessThan = function() { 1998 | function toBeLessThan() { 1999 | return { 2000 | 2001 | compare: function(actual, expected) { 2002 | return { 2003 | pass: actual < expected 2004 | }; 2005 | } 2006 | }; 2007 | } 2008 | 2009 | return toBeLessThan; 2010 | }; 2011 | getJasmineRequireObj().toBeNaN = function(j$) { 2012 | 2013 | function toBeNaN() { 2014 | return { 2015 | compare: function(actual) { 2016 | var result = { 2017 | pass: (actual !== actual) 2018 | }; 2019 | 2020 | if (result.pass) { 2021 | result.message = "Expected actual not to be NaN."; 2022 | } else { 2023 | result.message = "Expected " + j$.pp(actual) + " to be NaN."; 2024 | } 2025 | 2026 | return result; 2027 | } 2028 | }; 2029 | } 2030 | 2031 | return toBeNaN; 2032 | }; 2033 | 2034 | getJasmineRequireObj().toBeNull = function() { 2035 | 2036 | function toBeNull() { 2037 | return { 2038 | compare: function(actual) { 2039 | return { 2040 | pass: actual === null 2041 | }; 2042 | } 2043 | }; 2044 | } 2045 | 2046 | return toBeNull; 2047 | }; 2048 | 2049 | getJasmineRequireObj().toBeTruthy = function() { 2050 | 2051 | function toBeTruthy() { 2052 | return { 2053 | compare: function(actual) { 2054 | return { 2055 | pass: !!actual 2056 | }; 2057 | } 2058 | }; 2059 | } 2060 | 2061 | return toBeTruthy; 2062 | }; 2063 | 2064 | getJasmineRequireObj().toBeUndefined = function() { 2065 | 2066 | function toBeUndefined() { 2067 | return { 2068 | compare: function(actual) { 2069 | return { 2070 | pass: void 0 === actual 2071 | }; 2072 | } 2073 | }; 2074 | } 2075 | 2076 | return toBeUndefined; 2077 | }; 2078 | 2079 | getJasmineRequireObj().toContain = function() { 2080 | function toContain(util, customEqualityTesters) { 2081 | customEqualityTesters = customEqualityTesters || []; 2082 | 2083 | return { 2084 | compare: function(actual, expected) { 2085 | 2086 | return { 2087 | pass: util.contains(actual, expected, customEqualityTesters) 2088 | }; 2089 | } 2090 | }; 2091 | } 2092 | 2093 | return toContain; 2094 | }; 2095 | 2096 | getJasmineRequireObj().toEqual = function() { 2097 | 2098 | function toEqual(util, customEqualityTesters) { 2099 | customEqualityTesters = customEqualityTesters || []; 2100 | 2101 | return { 2102 | compare: function(actual, expected) { 2103 | var result = { 2104 | pass: false 2105 | }; 2106 | 2107 | result.pass = util.equals(actual, expected, customEqualityTesters); 2108 | 2109 | return result; 2110 | } 2111 | }; 2112 | } 2113 | 2114 | return toEqual; 2115 | }; 2116 | 2117 | getJasmineRequireObj().toHaveBeenCalled = function(j$) { 2118 | 2119 | function toHaveBeenCalled() { 2120 | return { 2121 | compare: function(actual) { 2122 | var result = {}; 2123 | 2124 | if (!j$.isSpy(actual)) { 2125 | throw new Error('Expected a spy, but got ' + j$.pp(actual) + '.'); 2126 | } 2127 | 2128 | if (arguments.length > 1) { 2129 | throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); 2130 | } 2131 | 2132 | result.pass = actual.calls.any(); 2133 | 2134 | result.message = result.pass ? 2135 | "Expected spy " + actual.and.identity() + " not to have been called." : 2136 | "Expected spy " + actual.and.identity() + " to have been called."; 2137 | 2138 | return result; 2139 | } 2140 | }; 2141 | } 2142 | 2143 | return toHaveBeenCalled; 2144 | }; 2145 | 2146 | getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { 2147 | 2148 | function toHaveBeenCalledWith(util) { 2149 | return { 2150 | compare: function() { 2151 | var args = Array.prototype.slice.call(arguments, 0), 2152 | actual = args[0], 2153 | expectedArgs = args.slice(1), 2154 | result = { pass: false }; 2155 | 2156 | if (!j$.isSpy(actual)) { 2157 | throw new Error('Expected a spy, but got ' + j$.pp(actual) + '.'); 2158 | } 2159 | 2160 | if (!actual.calls.any()) { 2161 | result.message = "Expected spy " + actual.and.identity() + " to have been called with " + j$.pp(expectedArgs) + " but it was never called."; 2162 | return result; 2163 | } 2164 | 2165 | if (util.contains(actual.calls.allArgs(), expectedArgs)) { 2166 | result.pass = true; 2167 | result.message = "Expected spy " + actual.and.identity() + " not to have been called with " + j$.pp(expectedArgs) + " but it was."; 2168 | } else { 2169 | result.message = "Expected spy " + actual.and.identity() + " to have been called with " + j$.pp(expectedArgs) + " but actual calls were " + j$.pp(actual.calls.allArgs()).replace(/^\[ | \]$/g, '') + "."; 2170 | } 2171 | 2172 | return result; 2173 | } 2174 | }; 2175 | } 2176 | 2177 | return toHaveBeenCalledWith; 2178 | }; 2179 | 2180 | getJasmineRequireObj().toMatch = function() { 2181 | 2182 | function toMatch() { 2183 | return { 2184 | compare: function(actual, expected) { 2185 | var regexp = new RegExp(expected); 2186 | 2187 | return { 2188 | pass: regexp.test(actual) 2189 | }; 2190 | } 2191 | }; 2192 | } 2193 | 2194 | return toMatch; 2195 | }; 2196 | 2197 | getJasmineRequireObj().toThrow = function(j$) { 2198 | 2199 | function toThrow(util) { 2200 | return { 2201 | compare: function(actual, expected) { 2202 | var result = { pass: false }, 2203 | threw = false, 2204 | thrown; 2205 | 2206 | if (typeof actual != "function") { 2207 | throw new Error("Actual is not a Function"); 2208 | } 2209 | 2210 | try { 2211 | actual(); 2212 | } catch (e) { 2213 | threw = true; 2214 | thrown = e; 2215 | } 2216 | 2217 | if (!threw) { 2218 | result.message = "Expected function to throw an exception."; 2219 | return result; 2220 | } 2221 | 2222 | if (arguments.length == 1) { 2223 | result.pass = true; 2224 | result.message = "Expected function not to throw, but it threw " + j$.pp(thrown) + "."; 2225 | 2226 | return result; 2227 | } 2228 | 2229 | if (util.equals(thrown, expected)) { 2230 | result.pass = true; 2231 | result.message = "Expected function not to throw " + j$.pp(expected) + "."; 2232 | } else { 2233 | result.message = "Expected function to throw " + j$.pp(expected) + ", but it threw " + j$.pp(thrown) + "."; 2234 | } 2235 | 2236 | return result; 2237 | } 2238 | }; 2239 | } 2240 | 2241 | return toThrow; 2242 | }; 2243 | 2244 | getJasmineRequireObj().toThrowError = function(j$) { 2245 | function toThrowError (util) { 2246 | return { 2247 | compare: function(actual) { 2248 | var threw = false, 2249 | thrown, 2250 | errorType, 2251 | message, 2252 | regexp, 2253 | name, 2254 | constructorName; 2255 | 2256 | if (typeof actual != "function") { 2257 | throw new Error("Actual is not a Function"); 2258 | } 2259 | 2260 | extractExpectedParams.apply(null, arguments); 2261 | 2262 | try { 2263 | actual(); 2264 | } catch (e) { 2265 | threw = true; 2266 | thrown = e; 2267 | } 2268 | 2269 | if (!threw) { 2270 | return fail("Expected function to throw an Error."); 2271 | } 2272 | 2273 | if (!(thrown instanceof Error)) { 2274 | return fail("Expected function to throw an Error, but it threw " + thrown + "."); 2275 | } 2276 | 2277 | if (arguments.length == 1) { 2278 | return pass("Expected function not to throw an Error, but it threw " + fnNameFor(thrown) + "."); 2279 | } 2280 | 2281 | if (errorType) { 2282 | name = fnNameFor(errorType); 2283 | constructorName = fnNameFor(thrown.constructor); 2284 | } 2285 | 2286 | if (errorType && message) { 2287 | if (thrown.constructor == errorType && util.equals(thrown.message, message)) { 2288 | return pass("Expected function not to throw " + name + " with message \"" + message + "\"."); 2289 | } else { 2290 | return fail("Expected function to throw " + name + " with message \"" + message + 2291 | "\", but it threw " + constructorName + " with message \"" + thrown.message + "\"."); 2292 | } 2293 | } 2294 | 2295 | if (errorType && regexp) { 2296 | if (thrown.constructor == errorType && regexp.test(thrown.message)) { 2297 | return pass("Expected function not to throw " + name + " with message matching " + regexp + "."); 2298 | } else { 2299 | return fail("Expected function to throw " + name + " with message matching " + regexp + 2300 | ", but it threw " + constructorName + " with message \"" + thrown.message + "\"."); 2301 | } 2302 | } 2303 | 2304 | if (errorType) { 2305 | if (thrown.constructor == errorType) { 2306 | return pass("Expected function not to throw " + name + "."); 2307 | } else { 2308 | return fail("Expected function to throw " + name + ", but it threw " + constructorName + "."); 2309 | } 2310 | } 2311 | 2312 | if (message) { 2313 | if (thrown.message == message) { 2314 | return pass("Expected function not to throw an exception with message " + j$.pp(message) + "."); 2315 | } else { 2316 | return fail("Expected function to throw an exception with message " + j$.pp(message) + 2317 | ", but it threw an exception with message " + j$.pp(thrown.message) + "."); 2318 | } 2319 | } 2320 | 2321 | if (regexp) { 2322 | if (regexp.test(thrown.message)) { 2323 | return pass("Expected function not to throw an exception with a message matching " + j$.pp(regexp) + "."); 2324 | } else { 2325 | return fail("Expected function to throw an exception with a message matching " + j$.pp(regexp) + 2326 | ", but it threw an exception with message " + j$.pp(thrown.message) + "."); 2327 | } 2328 | } 2329 | 2330 | function fnNameFor(func) { 2331 | return func.name || func.toString().match(/^\s*function\s*(\w*)\s*\(/)[1]; 2332 | } 2333 | 2334 | function pass(notMessage) { 2335 | return { 2336 | pass: true, 2337 | message: notMessage 2338 | }; 2339 | } 2340 | 2341 | function fail(message) { 2342 | return { 2343 | pass: false, 2344 | message: message 2345 | }; 2346 | } 2347 | 2348 | function extractExpectedParams() { 2349 | if (arguments.length == 1) { 2350 | return; 2351 | } 2352 | 2353 | if (arguments.length == 2) { 2354 | var expected = arguments[1]; 2355 | 2356 | if (expected instanceof RegExp) { 2357 | regexp = expected; 2358 | } else if (typeof expected == "string") { 2359 | message = expected; 2360 | } else if (checkForAnErrorType(expected)) { 2361 | errorType = expected; 2362 | } 2363 | 2364 | if (!(errorType || message || regexp)) { 2365 | throw new Error("Expected is not an Error, string, or RegExp."); 2366 | } 2367 | } else { 2368 | if (checkForAnErrorType(arguments[1])) { 2369 | errorType = arguments[1]; 2370 | } else { 2371 | throw new Error("Expected error type is not an Error."); 2372 | } 2373 | 2374 | if (arguments[2] instanceof RegExp) { 2375 | regexp = arguments[2]; 2376 | } else if (typeof arguments[2] == "string") { 2377 | message = arguments[2]; 2378 | } else { 2379 | throw new Error("Expected error message is not a string or RegExp."); 2380 | } 2381 | } 2382 | } 2383 | 2384 | function checkForAnErrorType(type) { 2385 | if (typeof type !== "function") { 2386 | return false; 2387 | } 2388 | 2389 | var Surrogate = function() {}; 2390 | Surrogate.prototype = type.prototype; 2391 | return (new Surrogate()) instanceof Error; 2392 | } 2393 | } 2394 | }; 2395 | } 2396 | 2397 | return toThrowError; 2398 | }; 2399 | 2400 | getJasmineRequireObj().version = function() { 2401 | return "2.0.0"; 2402 | }; 2403 | -------------------------------------------------------------------------------- /lib/run-jasmine.js: -------------------------------------------------------------------------------- 1 | // Usage: phantomjs run-jasmine.js ../sample.html 2 | // Generated by CoffeeScript 1.3.3 3 | (function() { 4 | var page, system, waitFor; 5 | 6 | system = require('system'); 7 | 8 | waitFor = function(testFx, onReady, timeOutMillis) { 9 | var condition, f, interval, start; 10 | if (timeOutMillis == null) { 11 | timeOutMillis = 3000; 12 | } 13 | start = new Date().getTime(); 14 | condition = false; 15 | f = function() { 16 | if ((new Date().getTime() - start < timeOutMillis) && !condition) { 17 | return condition = (typeof testFx === 'string' ? eval(testFx) : testFx()); 18 | } else { 19 | if (!condition) { 20 | console.log("'waitFor()' timeout"); 21 | return phantom.exit(1); 22 | } else { 23 | if (typeof onReady === 'string') { 24 | eval(onReady); 25 | } else { 26 | onReady(); 27 | } 28 | return clearInterval(interval); 29 | } 30 | } 31 | }; 32 | return interval = setInterval(f, 100); 33 | }; 34 | 35 | if (system.args.length !== 2) { 36 | console.log('Usage: phantomjs run-jasmine.js URL'); 37 | phantom.exit(1); 38 | } 39 | 40 | page = require('webpage').create(); 41 | 42 | page.onConsoleMessage = function(msg) { 43 | return console.log(msg); 44 | }; 45 | 46 | page.open(system.args[1], function(status) { 47 | if (status !== 'success') { 48 | console.log('Unable to access network'); 49 | return phantom.exit(1); 50 | } else { 51 | page.evaluate(function() { 52 | var original; 53 | original = jasmine.ExpectationResult; 54 | jasmine.ExpectationResult = function(params) { 55 | original.apply(this, [params]); 56 | if (!this.passed_ && !(this.trace.stack != null)) { 57 | try { 58 | throw new Error(this.message); 59 | } catch (e) { 60 | this.trace = e; 61 | return null; 62 | } 63 | } 64 | }; 65 | jasmine.ExpectationResult.prototype = original.prototype; 66 | window.COLOR_ES = { 67 | "black": "\x1b[30m", 68 | "red": "\x1b[31m", 69 | "green": "\x1b[32m", 70 | "yellow": "\x1b[33m", 71 | "blue": "\x1b[34m", 72 | "magenta": "\x1b[35m", 73 | "cyan": "\x1b[36m", 74 | "white": "\x1b[37m", 75 | "default": "\x1b[39m" 76 | }; 77 | return window.logWithColor = function(log, color) { 78 | if (!COLOR_ES[color]) { 79 | console.log(log); 80 | return; 81 | } 82 | return console.log("" + COLOR_ES[color] + log + COLOR_ES['default']); 83 | }; 84 | }); 85 | return waitFor(function() { 86 | return page.evaluate(function() { 87 | return document.body.querySelector('.symbolSummary .pending') === null; 88 | }); 89 | }, function() { 90 | var exitCode; 91 | exitCode = page.evaluate(function() { 92 | var el, failsCount, i, index, line, list, specsCount, stackTrace, _i, _j, _len, _len1, _ref; 93 | console.log(document.body.querySelector('.jasmine_reporter .duration').innerText); 94 | specsCount = document.body.querySelectorAll(".symbolSummary li").length; 95 | failsCount = document.body.querySelectorAll('.symbolSummary li.failed').length; 96 | if (failsCount === 0) { 97 | logWithColor("" + specsCount + " examples, 0 failures", 'green'); 98 | return 0; 99 | } 100 | logWithColor("" + specsCount + " examples, " + failsCount + " failures", 'red'); 101 | console.log("\nFailures:\n"); 102 | list = document.body.querySelectorAll('.results > #details > .specDetail.failed'); 103 | for (i = _i = 0, _len = list.length; _i < _len; i = ++_i) { 104 | el = list[i]; 105 | logWithColor(" " + (i + 1) + ") " + (el.querySelector('.description').innerText)); 106 | logWithColor(" " + (el.querySelector('.resultMessage.fail').innerText), 'red'); 107 | if (el.querySelector('.stackTrace')) { 108 | stackTrace = []; 109 | _ref = el.querySelector('.stackTrace').innerText.split(/\n/); 110 | for (index = _j = 0, _len1 = _ref.length; _j < _len1; index = ++_j) { 111 | line = _ref[index]; 112 | if (index === 0) { 113 | continue; 114 | } 115 | if (line.indexOf("__JASMINE_ROOT__") !== -1) { 116 | continue; 117 | } 118 | if (line.indexOf("/lib/jasmine-1.2.0/jasmine.js") !== -1) { 119 | continue; 120 | } 121 | if (line.indexOf("phantomjs://webpage.evaluate") !== -1) { 122 | continue; 123 | } 124 | logWithColor(" " + line, 'cyan'); 125 | } 126 | } 127 | console.log(""); 128 | } 129 | return 1; 130 | }); 131 | return phantom.exit(exitCode); 132 | }); 133 | } 134 | }); 135 | 136 | }).call(this); 137 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jquery.narrows", 3 | "version": "0.3.1", 4 | "description": "jQuery Select Narrowing Plugin", 5 | "main": "jquery.narrows.js", 6 | "directories": { 7 | "test": "test" 8 | }, 9 | "scripts": { 10 | "test": "echo \"Error: no test specified\" && exit 1" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git://github.com/monmonmon/jquery.narrows.git" 15 | }, 16 | "keywords": [ 17 | "jquery", 18 | "select", 19 | "hierselect" 20 | ], 21 | "author": "Shimon Yamada", 22 | "license": "MIT", 23 | "bugs": { 24 | "url": "https://github.com/monmonmon/jquery.narrows/issues" 25 | }, 26 | "devDependencies": { 27 | "grunt": "0.4.1", 28 | "grunt-contrib-watch": "0.5.3", 29 | "grunt-contrib-uglify": "0.2.4", 30 | "grunt-contrib-jshint": "~0.6.4", 31 | "grunt-contrib-jasmine": "~0.5.2" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /sample-jasmine-2.0.0.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | jquery.narrows.js 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 41 | 42 | 43 | 44 |

例1

45 |
46 |

基本的な「親→子」の階層関係

47 | 53 | 65 |
 66 | $("#ex1-food-category").narrows("#ex1-food");
 67 | 
68 |
69 | 70 |

例2

71 |
72 |

親selectが未選択の場合、子selectは全て選択可能

73 | 79 | 91 |
 92 | $("#ex2-food-category").narrows("#ex2-food", {
 93 |     disable_if_parent_is_null: false
 94 | });
 95 | 
96 |
97 | 98 |

例3

99 |
100 |

「親→子→孫」の3世代

101 | 110 | 143 | 191 |
192 | $("#ex3-continent").narrows("#ex3-country");
193 | $("#ex3-country").narrows("#ex3-city");
194 | 
195 |
196 | 197 |

例4

198 |
199 |

「親→子1、子2」
1つの親selectの選択結果が複数の子selectの選択肢に同時に影響

200 | 206 | 218 | 232 |
233 | $("#ex4-cuisine").narrows("#ex4-food, #ex4-alcohol");
234 | 
235 |
236 | 237 |

例5

238 |
239 |

「親1、親2→子」
複数の親selectの選択結果が1つの子selectの選択肢に影響。Country と Category 両方を選択して初めて Menu が選択可能になります

240 | 246 | 252 | 267 |
268 | $("#ex5-country, #ex5-category").narrows("#ex5-menu");
269 | 
270 |
271 | 272 |

例6

273 |
274 |

275 | 子selectの1つのoptionが、親selectの複数のoptionにマッチ。
276 | うどんやカレーは食べ物ですが、飲み物であると主張する人々もいます。 277 |

278 | 283 | 291 |
292 | <select id="ex6-category">
293 |   <option value="">-- Food Category --</option>
294 |   <option value="food">食べ物</option>
295 |   <option value="drink">飲み物</option>
296 | </select>
297 | <select id="ex6-menu">
298 |   <option value="">-- Menu --</option>
299 |   <option value="sushi"     data-ex6-category="food">寿司</option>
300 |   <option value="tempura"   data-ex6-category="food">天ぷら</option>
301 |   <option value="green-tea" data-ex6-category="drink">お茶</option>
302 |   <option value="udon"      data-ex6-category="food,drink">うどん</option><!-- data-ex6-category に複数のカテゴリを指定 -->
303 |   <option value="dumpling"  data-ex6-category="food,drink">カレー</option><!-- 同上 -->
304 | </select>
305 | 
306 |
307 | $("#ex6-category").narrows("#ex6-menu", {
308 |     allow_multiple_parent_values: true
309 | });
310 | 
311 |
312 | 313 | 314 | 315 | -------------------------------------------------------------------------------- /sample.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | jquery.narrows.js 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 42 | 43 | 44 | 45 |

例1

46 |
47 |

基本的な「親→子」の階層関係

48 | 54 | 66 |
 67 | $("#ex1-food-category").narrows("#ex1-food");
 68 | 
69 |
70 | 71 |

例2

72 |
73 |

親selectが未選択の場合、子selectは全て選択可能

74 | 80 | 92 |
 93 | $("#ex2-food-category").narrows("#ex2-food", {
 94 |     disable_if_parent_is_null: false
 95 | });
 96 | 
97 |
98 | 99 |

例3

100 |
101 |

「親→子→孫」の3世代

102 | 111 | 144 | 192 |
193 | $("#ex3-continent").narrows("#ex3-country");
194 | $("#ex3-country").narrows("#ex3-city");
195 | 
196 |
197 | 198 |

例4

199 |
200 |

「親→子1、子2」
1つの親selectの選択結果が複数の子selectの選択肢に同時に影響

201 | 207 | 219 | 233 |
234 | $("#ex4-cuisine").narrows("#ex4-food, #ex4-alcohol");
235 | 
236 |
237 | 238 |

例5

239 |
240 |

「親1、親2→子」
複数の親selectの選択結果が1つの子selectの選択肢に影響。Country と Category 両方を選択して初めて Menu が選択可能になります

241 | 247 | 253 | 268 |
269 | $("#ex5-country, #ex5-category").narrows("#ex5-menu");
270 | 
271 |
272 | 273 |

例6

274 |
275 |

276 | 子selectの1つのoptionが、親selectの複数のoptionにマッチ。
277 | うどんやカレーは食べ物ですが、飲み物であると主張する人々もいます。 278 |

279 | 284 | 292 |
293 | <select id="ex6-category">
294 |   <option value="">-- Food Category --</option>
295 |   <option value="food">食べ物</option>
296 |   <option value="drink">飲み物</option>
297 | </select>
298 | <select id="ex6-menu">
299 |   <option value="">-- Menu --</option>
300 |   <option value="sushi"     data-ex6-category="food">寿司</option>
301 |   <option value="tempura"   data-ex6-category="food">天ぷら</option>
302 |   <option value="green-tea" data-ex6-category="drink">お茶</option>
303 |   <option value="udon"      data-ex6-category="food,drink">うどん</option><!-- data-ex6-category に複数のカテゴリを指定 -->
304 |   <option value="dumpling"  data-ex6-category="food,drink">カレー</option><!-- 同上 -->
305 | </select>
306 | 
307 |
308 | $("#ex6-category").narrows("#ex6-menu", {
309 |     allow_multiple_parent_values: true
310 | });
311 | 
312 |
313 | 314 | 315 | 316 | -------------------------------------------------------------------------------- /spec/narrowsSpec.js: -------------------------------------------------------------------------------- 1 | $(function () { 2 | // 例1:親→子 3 | describe('例1', function() { 4 | // jquery instances of the select elements 5 | var $category = $('#ex1-food-category'); 6 | var $food = $('#ex1-food'); 7 | 8 | // 各テストの最初に選択状態を初期化 9 | beforeEach(function() { 10 | $category.val('').trigger('change'); 11 | $food.val('').trigger('change'); 12 | }); 13 | 14 | it('food は初期状態で disabled', function () { 15 | expect($category.is(':disabled')).toBe(false); 16 | expect($food.is(':disabled')).toBe(true); 17 | }); 18 | 19 | it('category で "meat" を選択したら food は肉に絞り込まれる', function () { 20 | // category を選択 21 | $category.val('meat').trigger('change'); 22 | // food の disabled 解除 23 | expect($category.is(':disabled')).toBe(false); 24 | expect($food.is(':disabled')).toBe(false); 25 | // value="" を含め絞りこまれたoptionは2つ以上 26 | expect($food.find('option').size()).toBeGreaterThan(1); 27 | // option の data-xx 属性が全て "meat" 28 | $food.find('option').each(function () { 29 | if ($(this).val()) { 30 | expect($(this).data('ex1-food-category')).toEqual('meat'); 31 | } 32 | }); 33 | }); 34 | 35 | it('category で value="" を選択したら food は disabled', function () { 36 | // category, food を選択してから 37 | $category.val('meat').trigger('change'); 38 | $food.val('beef').trigger('change'); 39 | // category を非選択状態にする 40 | $category.val('').trigger('change'); 41 | // food は disabled 42 | expect($category.is(':disabled')).toBe(false); 43 | expect($food.is(':disabled')).toBe(true); 44 | // food は value="" 45 | expect($food.val()).toBe(''); 46 | }); 47 | }); 48 | 49 | // 例2:親→子、親selectが未選択の場合、子selectは全て選択可能 50 | describe('例2', function() { 51 | // jquery instances of the select elements 52 | var $category = $('#ex2-food-category'); 53 | var $food = $('#ex2-food'); 54 | 55 | // 各テストの最初に選択状態を初期化 56 | beforeEach(function() { 57 | $category.val('').trigger('change'); 58 | $food.val('').trigger('change'); 59 | }); 60 | 61 | it('category, food とも初期状態で enabled', function () { 62 | expect($category.is(':disabled')).toBe(false); 63 | expect($food.is(':disabled')).toBe(false); 64 | }); 65 | 66 | it('category で "meat" を選択したら food は肉に絞り込まれる', function () { 67 | // category を選択 68 | $category.val('meat').trigger('change'); 69 | // foodのdisabled解除 70 | expect($category.is(':disabled')).toBe(false); 71 | expect($food.is(':disabled')).toBe(false); 72 | // value="" を含め絞りこまれたoptionは2つ以上 73 | expect($food.find('option').size()).toBeGreaterThan(1); 74 | // option の data-xx 属性が全て "meat" 75 | $food.find('option').each(function () { 76 | if ($(this).val()) { 77 | expect($(this).data('ex2-food-category')).toEqual('meat'); 78 | } 79 | }); 80 | }); 81 | 82 | it('category で value="" を選択したら、food は全ての option が選択可能になる', function () { 83 | // category, food を選択してから 84 | $category.val('meat').trigger('change'); 85 | $food.val('beef').trigger('change'); 86 | // category を非選択状態にする 87 | $category.val('').trigger('change'); 88 | // food は enabled 89 | expect($category.is(':disabled')).toBe(false); 90 | expect($food.is(':disabled')).toBe(false); 91 | // food の選択肢は様々 92 | var categories = $food.find('option[value!=""]').map(function () { 93 | return $(this).data('ex2-food-category'); 94 | }).get(); 95 | expect(categories.indexOf('meat')).not.toBe(-1); 96 | expect(categories.indexOf('vegetable')).not.toBe(-1); 97 | expect(categories.indexOf('fruit')).not.toBe(-1); 98 | }); 99 | }); 100 | 101 | // 例3:親→子→孫 102 | describe('例3', function() { 103 | // jquery instances of the select elements 104 | var $continent = $('#ex3-continent'); 105 | var $country = $('#ex3-country'); 106 | var $city = $('#ex3-city'); 107 | 108 | // 各テストの最初に選択状態を初期化 109 | beforeEach(function() { 110 | $continent.val('').trigger('change'); 111 | $country.val('').trigger('change'); 112 | $city.val('').trigger('change'); 113 | }); 114 | 115 | it('country, city は初期状態で disabled', function () { 116 | expect($continent.is(':disabled')).toBe(false); 117 | expect($country.is(':disabled')).toBe(true); 118 | expect($city.is(':disabled')).toBe(true); 119 | }); 120 | 121 | it('continent で "asia" を選択したら country はアジアの国に絞り込まれる', function () { 122 | // continent を選択 123 | $continent.val('asia').trigger('change'); 124 | // countryのdisabled解除、cityはdisabledのまま 125 | expect($continent.is(':disabled')).toBe(false); 126 | expect($country.is(':disabled')).toBe(false); 127 | expect($city.is(':disabled')).toBe(true); 128 | // value="" を含め絞りこまれたoptionは2つ以上 129 | expect($country.find('option').size()).toBeGreaterThan(1); 130 | // option の data-xx 属性が全て "asia" 131 | $country.find('option').each(function () { 132 | if ($(this).val()) { 133 | expect($(this).data('ex3-continent')).toEqual('asia'); 134 | } 135 | }); 136 | }); 137 | 138 | it('continent で "asia", country で "japan" を選択したら city は日本の都市に絞り込まれる', function () { 139 | // continent, country を選択 140 | $continent.val('asia').trigger('change'); 141 | $country.val('japan').trigger('change'); 142 | // disabled全て解除 143 | expect($continent.is(':disabled')).toBe(false); 144 | expect($country.is(':disabled')).toBe(false); 145 | expect($city.is(':disabled')).toBe(false); 146 | // value="" を含め絞りこまれたoptionは2つ以上 147 | expect($city.find('option').size()).toBeGreaterThan(1); 148 | // option の data-xx 属性が全て "asia" 149 | $city.find('option').each(function () { 150 | if ($(this).val()) { 151 | expect($(this).data('ex3-country')).toEqual('japan'); 152 | } 153 | }); 154 | }); 155 | 156 | it('continent で value="" を選択したら country, city は disabled', function () { 157 | // continent, country, city を選択してから 158 | $continent.val('asia').trigger('change'); 159 | $country.val('japan').trigger('change'); 160 | $city.val('tokyo').trigger('change'); 161 | // continent を非選択状態にする 162 | $continent.val('').trigger('change'); 163 | // country, city は disabled 164 | expect($continent.is(':disabled')).toBe(false); 165 | expect($country.is(':disabled')).toBe(true); 166 | expect($city.is(':disabled')).toBe(true); 167 | // country, city は value="" 168 | expect($country.val()).toBe(''); 169 | expect($city.val()).toBe(''); 170 | }); 171 | }); 172 | 173 | // 例4:親→子1、子2 174 | describe('例4', function() { 175 | // jquery instances of the select elements 176 | var $cuisine = $('#ex4-cuisine'); 177 | var $food = $('#ex4-food'); 178 | var $alcohol = $('#ex4-alcohol'); 179 | 180 | // 各テストの最初に選択状態を初期化 181 | beforeEach(function() { 182 | $cuisine.val('').trigger('change'); 183 | $food.val('').trigger('change'); 184 | $alcohol.val('').trigger('change'); 185 | }); 186 | 187 | it('food, alcohol は初期状態で disabled', function () { 188 | expect($cuisine.is(':disabled')).toBe(false); 189 | expect($food.is(':disabled')).toBe(true); 190 | expect($alcohol.is(':disabled')).toBe(true); 191 | }); 192 | 193 | it('cuisine で "japanese" を選択したら food, alcohol 両方とも絞り込まれる', function () { 194 | // cuisine で japanese を選択 195 | $cuisine.val('japanese').trigger('change'); 196 | // food の disabled が解け、japanese で絞り込まれる 197 | expect($food.is(':disabled')).toBe(false); 198 | expect($food.find('option').size()).toBeGreaterThan(1); 199 | $food.find('option').each(function () { 200 | if ($(this).val()) { 201 | expect($(this).data('ex4-cuisine')).toEqual('japanese'); 202 | } 203 | }); 204 | // alcohol の disabled が解け、japanese で絞り込まれる 205 | expect($alcohol.is(':disabled')).toBe(false); 206 | expect($alcohol.find('option').size()).toBeGreaterThan(1); 207 | $alcohol.find('option').each(function () { 208 | if ($(this).val()) { 209 | expect($(this).data('ex4-cuisine')).toEqual('japanese'); 210 | } 211 | }); 212 | }); 213 | 214 | it('cuisine で value="" を選択したら food, alcohol は disabled', function () { 215 | // select cuisine 216 | $cuisine.val('japanese').trigger('change'); 217 | // ... and reset 218 | $cuisine.val('').trigger('change'); 219 | expect($food.is(':disabled')).toBe(true); 220 | expect($alcohol.is(':disabled')).toBe(true); 221 | }); 222 | }); 223 | 224 | // 例5:親1、親2→子 225 | describe('例5', function() { 226 | // jquery instances of the select elements 227 | var $country = $('#ex5-country'); 228 | var $category = $('#ex5-category'); 229 | var $menu = $('#ex5-menu'); 230 | 231 | // 各テストの最初に選択状態を初期化 232 | beforeEach(function() { 233 | $country.val('').trigger('change'); 234 | $category.val('').trigger('change'); 235 | $menu.val('').trigger('change'); 236 | }); 237 | 238 | it('menu は初期状態で disabled', function () { 239 | expect($country.is(':disabled')).toBe(false); 240 | expect($category.is(':disabled')).toBe(false); 241 | expect($menu.is(':disabled')).toBe(true); 242 | }); 243 | 244 | it('country だけ選択しても menu は disabled のまま', function () { 245 | // select country 246 | $country.val('japanese').trigger('change'); 247 | expect($menu.is(':disabled')).toBe(true); 248 | }); 249 | 250 | it('category だけ選択しても menu は disabled のまま', function () { 251 | // select category 252 | $category.val('food').trigger('change'); 253 | expect($menu.is(':disabled')).toBe(true); 254 | }); 255 | 256 | it('country で "japanese", category で "food" を選択したら menu が絞り込まれる', function () { 257 | // select country & category 258 | $country.val('japanese').trigger('change'); 259 | $category.val('food').trigger('change'); 260 | expect($menu.find('option').size()).toBeGreaterThan(1); 261 | $menu.find('option').each(function () { 262 | if ($(this).val()) { 263 | expect($(this).data('ex5-country')).toEqual('japanese'); 264 | expect($(this).data('ex5-category')).toEqual('food'); 265 | } 266 | }); 267 | }); 268 | 269 | it('country で value="" を選択したら menu は disabled', function () { 270 | // 一度両方選択してから 271 | $country.val('japanese').trigger('change'); 272 | $category.val('food').trigger('change'); 273 | // country を非選択状態にする 274 | $country.val('').trigger('change'); 275 | expect($menu.is(':disabled')).toBe(true); 276 | expect($menu.val()).toBe(''); 277 | }); 278 | 279 | it('category で value="" を選択したら menu は disabled', function () { 280 | // 一度両方選択してから 281 | $country.val('japanese').trigger('change'); 282 | $category.val('food').trigger('change'); 283 | // category を非選択状態にする 284 | $category.val('').trigger('change'); 285 | expect($menu.is(':disabled')).toBe(true); 286 | expect($menu.val()).toBe(''); 287 | }); 288 | }); 289 | 290 | // 例6:親→子 291 | describe('例6', function() { 292 | // jquery instances of the select elements 293 | var $category = $('#ex6-category'); 294 | var $menu = $('#ex6-menu'); 295 | 296 | // 各テストの最初に選択状態を初期化 297 | beforeEach(function() { 298 | $category.val('').trigger('change'); 299 | $menu.val('').trigger('change'); 300 | }); 301 | 302 | it('menu は初期状態で disabled', function () { 303 | expect($category.is(':disabled')).toBe(false); 304 | expect($menu.is(':disabled')).toBe(true); 305 | }); 306 | 307 | it('category で "food" を選択したら menu にうどん、カレーが含まれる', function () { 308 | // category で food を選択 309 | $category.val('food').trigger('change'); 310 | // menu にうどんが含まれることを確認 311 | expect($menu.find('option[value=udon]').size()).toBe(1); 312 | }); 313 | 314 | it('category で "drink" を選択しても menu にうどん、カレーが含まれる', function () { 315 | // category で drink を選択 316 | $category.val('drink').trigger('change'); 317 | // menu にうどんが含まれることを確認 318 | expect($menu.find('option[value=udon]').size()).toBe(1); 319 | }); 320 | }); 321 | 322 | // (dummy spec) reset all selections after the tests 323 | describe('(dummy spec)', function() { 324 | it('reset all selects', function () { 325 | $('#ex1-food-category').val('').trigger('change'); 326 | $('#ex1-food').val('').trigger('change'); 327 | $('#ex2-food-category').val('').trigger('change'); 328 | $('#ex2-food').val('').trigger('change'); 329 | $('#ex3-continent').val('').trigger('change'); 330 | $('#ex3-country').val('').trigger('change'); 331 | $('#ex3-city').val('').trigger('change'); 332 | $('#ex4-cuisine').val('').trigger('change'); 333 | $('#ex4-food').val('').trigger('change'); 334 | $('#ex4-alcohol').val('').trigger('change'); 335 | $('#ex5-country').val('').trigger('change'); 336 | $('#ex5-category').val('').trigger('change'); 337 | $('#ex5-menu').val('').trigger('change'); 338 | $('#ex6-category').val('').trigger('change'); 339 | $('#ex6-menu').val('').trigger('change'); 340 | }); 341 | }); 342 | }); 343 | --------------------------------------------------------------------------------