Setup and docs for unit testing javascript in browser and node.js
BrainDoctor committed
Jul 17, 2017 at 15:25 UTC
1fe557fe3d06f79f2f1c2db1684eeedccf2dc8d8
8 files changed
+1220
.gitignore
+4
@@ -68,6 +68,10 @@ web/gadget.xml
68
web/index_new.html
69
web/version.txt
70
71
+# related to karma/javascript/node
72
+node_modules/
73
+coverage/
74
+
75
system/netdata-lsb
76
system/netdata-openrc
77
system/netdata-init-d
package.json
new
+12
@@ -0,0 +1,12 @@
1
+{
2
+ "devDependencies": {
3
+ "jasmine": "^2.6.0",
4
+ "jasmine-core": "^2.6.4",
5
+ "jasmine-node": "^1.14.5",
6
+ "karma": "^1.7.0",
7
+ "karma-chrome-launcher": "^2.2.0",
8
+ "karma-coverage": "^1.1.1",
9
+ "karma-firefox-launcher": "^1.0.1",
10
+ "karma-jasmine": "^1.1.0"
11
+ }
12
+}
tests/README.md
new
+131
@@ -0,0 +1,131 @@
1
+This readme is a manual on how to get started with unit testing on javascript and nodejs
2
+
3
+Original author: BrainDoctor (github), July 2017
4
+
5
+# Installation
6
+
7
+Tested on Linux Mint 18.2 Sara (Ubuntu/debian derivative)
8
+
9
+Make sure you are the user who is developer (permissions, except sudo ofc)
10
+
11
+```sh
12
+sudo apt-get install nodejs npm chromium-browser
13
+
14
+cd /path/to/your/netdata
15
+
16
+npm install
17
+```
18
+
19
+That should install the necessary node modules.
20
+
21
+Other browsers work too (Chrome, Firefox). However, only the Chromium Browser 59 has been tested for headless unit testing.
22
+
23
+## Versions
24
+
25
+The commands above leave me with the following versions (July 2017):
26
+
27
+ - nodejs: v4.2.6
28
+ - npm: 3.5.2
29
+ - chromium-browser: 59.0.3071.109
30
+ - WebStorm (optional): 2017.1.4
31
+
32
+# Configuration
33
+
34
+## NPM
35
+
36
+The dependencies are installed in `netdata/package.json`. If you install a new NPM module, it gets added here. Future developers just need to execute `npm install` and every dep gets added automatically.
37
+
38
+## Karma
39
+
40
+Karma configuration is in `tests/web/karma.conf.js`. Documentation is provided via comments.
41
+
42
+## WebStorm
43
+
44
+If you use the JetBrains WebStorm IDE, you can integrate the karma runtime.
45
+
46
+### for Karma (Client side testing)
47
+
48
+Headless Chromium:
49
+1. Run > Edit Configurations
50
+2. "+" > Karma
51
+3. - Name: Karma Headless Chromium
52
+ - Configuration file: /path/to/your/netdata/tests/web/karma.conf.js
53
+ - Browsers to start: ChromiumHeadless
54
+ - Node interpreter: /usr/bin/nodejs (MUST be absolute, NVM works too)
55
+ - Karma package: /path/to/your/netdata/node_modules/karma
56
+
57
+GUI Chromium is similar:
58
+1. Run > Edit Configurations
59
+2. "+" > Karma
60
+3. - Name: Karma Chromium
61
+ - Configuration file: /path/to/your/netdata/tests/web/karma.conf.js
62
+ - Browsers to start: Chromium
63
+ - Node interpreter: /usr/bin/nodejs (MUST be absolute, NVM works too)
64
+ - Karma package: /path/to/your/netdata/node_modules/karma
65
+
66
+You may add other browsers too (comma separated). With the "Browsers to start" field you can override any settings in karma.conf.js.
67
+
68
+Also it is recommended to install WebStorm IDE Extension/Addon to Chrome/Chromium for awesome debugging.
69
+
70
+### for node.d plugins (nodejs)
71
+
72
+1. Run > Edit Configurations
73
+2. "+" > Node.js
74
+3. - Name: Node.d plugins
75
+ - Node interpreter: /usr/bin/nodejs (MUST be absolute, NVM works too)
76
+ - JavaScript file: node_modules/jasmine-node/bin/jasmine-node
77
+ - Application parameters: --captureExceptions tests/node.d
78
+
79
+**ATTENTION**
80
+
81
+The jasmine-node npm package includes an outdated jasmine on version 1.3.1.
82
+
83
+I haven't figured out yet how to switch to newer 2.6 versions. So it may contain bugs or lacks features.
84
+
85
+# Running
86
+
87
+## In WebStorm
88
+
89
+Just run the configured run configurations and they produce nice test trees:
90
+
91
+
92
+## From CLI
93
+
94
+### Karma
95
+
96
+```sh
97
+cd /path/to/your/netdata
98
+
99
+nodejs ./node_modules/karma/bin/karma start tests/web/karma.conf.js --single-run=true --browsers=ChromiumHeadless
100
+```
101
+will start the karma server, start chromium in headless mode and exit.
102
+
103
+If a test fails, it produces even a stack trace:
104
+
105
+
106
+### Node.d plugins
107
+
108
+```sh
109
+cd /path/to/your/netdata
110
+
111
+nodejs node_modules/jasmine-node/bin/jasmine-node --captureExceptions tests/node.d
112
+```
113
+
114
+will run the tests in `tests/node.d` and produce a stacktrace too on error:
115
+
116
+
117
+## Coverage
118
+
119
+### Karma
120
+
121
+A nice HTML is produced from Karma which shows which code paths were executed. It is located somewhere in `/path/to/your/netdata/coverage/`
122
+
123
+### Node.d
124
+
125
+Apparently, jasmine-node can produce a junit report with the `--junitreport` flag. But that output was not very useful. Maybe it's configurable?
126
+
127
+## CI
128
+
129
+The karma and node.d runners can be integrated in Travis (AFAIK), but that is outside my ability.
130
+
131
+Note: Karma is for browser-testing. On a build server, no GUI or browser might by available, unless browsers support headless mode.
\ No newline at end of file
tests/node.d/fronius.spec.js
new
+58
@@ -0,0 +1,58 @@
1
+"use strict";
2
+// delete these comments if not needed anymore.
3
+
4
+var netdata = require("../../node.d/node_modules/netdata");
5
+var fronius = require("../../node.d/fronius.node");
6
+
7
+describe("fronius chart creation", function () {
8
+
9
+ beforeEach(function () {
10
+ netdata.options.DEBUG = true;
11
+ });
12
+
13
+ it("should return a basic chart definition", function () {
14
+ // act
15
+ var result = fronius.createBasicDimension("id", "name", 2);
16
+ // assert
17
+ expect(result.divisor).toBe(2);
18
+ expect(result.id).toBe("id");
19
+ expect(result.algorithm).toEqual("absolute");
20
+ expect(result.multiplier).toBe(1);
21
+ });
22
+
23
+ it("will fail", function () {
24
+ netdata.debug("test");
25
+
26
+ throw new Error("expected failure to test unit test runner");
27
+ });
28
+
29
+});
30
+
31
+describe("fronius data parsing", function () {
32
+
33
+ var service = netdata.service({
34
+ name: "fronius",
35
+ module: this
36
+ });
37
+
38
+ beforeEach(function () {
39
+ // change this to enable debug log
40
+ netdata.options.DEBUG = false;
41
+ });
42
+
43
+ it("should return a parsed value", function () {
44
+ // arrange
45
+ netdata.send = jasmine.createSpy("send");
46
+ // act
47
+ fronius.processResponse(service, createFakeResponse());
48
+ var result = netdata.send.calls[0].args[0];
49
+ // assert
50
+ expect(result).toContain("SET p_grid = -3431");
51
+ });
52
+
53
+ function createFakeResponse() {
54
+ // this is a faked JSON response from the server.
55
+ // Used with freeformatter.com/json-escape.html to escape the json and turn it into a string.
56
+ return "{\r\n\t\"Head\" : {\r\n\t\t\"RequestArguments\" : {},\r\n\t\t\"Status\" : {\r\n\t\t\t\"Code\" : 0,\r\n\t\t\t\"Reason\" : \"\",\r\n\t\t\t\"UserMessage\" : \"\"\r\n\t\t},\r\n\t\t\"Timestamp\" : \"2017-07-17T16:01:04+02:00\"\r\n\t},\r\n\t\"Body\" : {\r\n\t\t\"Data\" : {\r\n\t\t\t\"Site\" : {\r\n\t\t\t\t\"Mode\" : \"meter\",\r\n\t\t\t\t\"P_Grid\" : -3430.729923,\r\n\t\t\t\t\"P_Load\" : -910.270077,\r\n\t\t\t\t\"P_Akku\" : null,\r\n\t\t\t\t\"P_PV\" : 4341,\r\n\t\t\t\t\"rel_SelfConsumption\" : 20.969133,\r\n\t\t\t\t\"rel_Autonomy\" : 100,\r\n\t\t\t\t\"E_Day\" : 57230,\r\n\t\t\t\t\"E_Year\" : 6425915.5,\r\n\t\t\t\t\"E_Total\" : 15388710,\r\n\t\t\t\t\"Meter_Location\" : \"grid\"\r\n\t\t\t},\r\n\t\t\t\"Inverters\" : {\r\n\t\t\t\t\"1\" : {\r\n\t\t\t\t\t\"DT\" : 123,\r\n\t\t\t\t\t\"P\" : 4341,\r\n\t\t\t\t\t\"E_Day\" : 57230,\r\n\t\t\t\t\t\"E_Year\" : 6425915.5,\r\n\t\t\t\t\t\"E_Total\" : 15388710\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}"
57
+ }
58
+});
tests/web/easypiechart.spec.js
new
+58
@@ -0,0 +1,58 @@
1
+// delete these comments if not needed anymore.
2
+
3
+describe("percentage calculations for easy pie charts", function () {
4
+
5
+ // some easy functions to test. incomplete yet.
6
+ it('should return 50 if positive value between min and max', function () {
7
+ // act
8
+ var result = NETDATA.easypiechartPercentFromValueMinMax(1, 0, 2);
9
+ // assert
10
+ expect(result).toBe(50);
11
+ });
12
+
13
+ it('should return 0.1 if value is zero', function () {
14
+ // act
15
+ var result = NETDATA.easypiechartPercentFromValueMinMax(0, 0, 2);
16
+ // assert
17
+ expect(result).toBe(0.1);
18
+ });
19
+
20
+});
21
+
22
+
23
+// with xdescribe, this is skipped.
24
+// Delete the x to enable again and let it fail to test the build
25
+describe('creation of easy pie charts', function () {
26
+
27
+ beforeAll(function () {
28
+ // karma stores the loaded files relative to "base/".
29
+ // This command is needed to load HTML fixtures
30
+ jasmine.getFixtures().fixturesPath = "base/tests/web/fixtures";
31
+ });
32
+
33
+ it('should create new chart', function () {
34
+ // arrange
35
+ // Theoretically we can load some html. What about jquery? could this work?
36
+ // https://stackoverflow.com/questions/5337481/spying-on-jquery-selectors-in-jasmine
37
+ loadFixtures("easypiechart.creation.fixture1.html");
38
+
39
+ // for easy pie chart, we can fake the data result:
40
+ var data = {
41
+ result: [5]
42
+ };
43
+ // act
44
+ var result = NETDATA.easypiechartChartCreate(createState(), data);
45
+ // assert
46
+ expect(result).toBe(true);
47
+ });
48
+
49
+ function createState() {
50
+ // create a fake state with only needed properties? Spying? not figured it out yet...
51
+ return {
52
+ tmp: {
53
+
54
+ }
55
+ };
56
+ }
57
+
58
+});
\ No newline at end of file
tests/web/fixtures/easypiechart.creation.fixture1.html
new
+6
@@ -0,0 +1,6 @@
1
+<div data-netdata="system.cpu"
2
+ data-chart-library="easypiechart"
3
+ data-width="5%"
4
+ data-height="20"
5
+ data-after="-30"
6
+></div>
\ No newline at end of file
tests/web/karma.conf.js
new
+110
@@ -0,0 +1,110 @@
1
+// Karma configuration
2
+// Generated on Sun Jul 16 2017 02:28:05 GMT+0200 (CEST)
3
+
4
+module.exports = function (config) {
5
+ config.set({
6
+
7
+ // base path that will be used to resolve all patterns (eg. files, exclude)
8
+ // this path should always resolve so that "." is the "netdata" root folder.
9
+ basePath: '../../',
10
+
11
+ // frameworks to use
12
+ // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
13
+ frameworks: ['jasmine'],
14
+
15
+
16
+ // list of files / patterns to load in the browser
17
+ files: [
18
+ // order matters! load jquery libraries first
19
+ 'web/lib/jquery*.js',
20
+ // our jasmine libs and fixtures
21
+ 'tests/web/lib/*.js',
22
+ 'tests/web/fixtures/*.html',
23
+ // then bootstrap
24
+ 'web/lib/bootstrap*.js',
25
+ // then the rest
26
+ 'web/lib/perfect-scrollbar*.js',
27
+ 'web/lib/dygraph*.js',
28
+ 'web/lib/gauge*.js',
29
+ 'web/lib/morris*.js',
30
+ 'web/lib/raphael*.js',
31
+ 'web/lib/tableExport*.js',
32
+ 'web/lib/d3*.js',
33
+ 'web/lib/c3*.js',
34
+ // some CSS
35
+ 'web/css/*.css',
36
+ 'web/dashboard.css',
37
+ // our dashboard
38
+ 'web/dashboard.js',
39
+ // finally our test specs
40
+ 'tests/web/*.spec.js',
41
+ ],
42
+
43
+
44
+ // list of files to exclude
45
+ exclude: [],
46
+
47
+
48
+ // preprocess matching files before serving them to the browser
49
+ // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
50
+ preprocessors: {
51
+ 'web/dashboard.js': ['coverage']
52
+ },
53
+
54
+
55
+ // test results reporter to use
56
+ // possible values: 'dots', 'progress'
57
+ // available reporters: https://npmjs.org/browse/keyword/karma-reporter
58
+ reporters: ['progress', 'coverage'],
59
+
60
+ // optionally, configure the reporter
61
+ coverageReporter: {
62
+ type : 'html',
63
+ dir : 'coverage/'
64
+ },
65
+
66
+ // web server port
67
+ port: 9876,
68
+
69
+
70
+ // enable / disable colors in the output (reporters and logs)
71
+ colors: true,
72
+
73
+
74
+ // level of logging
75
+ // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
76
+ logLevel: config.LOG_INFO,
77
+
78
+
79
+ // enable / disable watching file and executing tests whenever any file changes
80
+ autoWatch: false,
81
+ // not needed with WebStorm. Just hit Alt+Shift+R to rerun.
82
+
83
+ // start these browsers
84
+ // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
85
+ browsers: ['Chromium', 'ChromiumHeadless'],
86
+
87
+ customLaunchers: {
88
+ // Headless browsers could be useful for CI integration, if installed.
89
+ ChromiumHeadless: {
90
+ // needs Chrome/Chromium version >= 59
91
+ // see https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md
92
+ base: "Chromium",
93
+ flags: [
94
+ "--headless",
95
+ "--disable-gpu",
96
+ // Without a remote debugging port, Chromium exits immediately.
97
+ "--remote-debugging-port=9222"
98
+ ]
99
+ }
100
+ },
101
+
102
+ // Continuous Integration mode
103
+ // if true, Karma captures browsers, runs the tests and exits
104
+ singleRun: false,
105
+
106
+ // Concurrency level
107
+ // how many browser should be started simultaneous
108
+ concurrency: Infinity
109
+ })
110
+};
tests/web/lib/jasmine-jquery.js
new
+841
@@ -0,0 +1,841 @@
1
+/*!
2
+ Jasmine-jQuery: a set of jQuery helpers for Jasmine tests.
3
+
4
+ Version 2.1.1
5
+
6
+ https://github.com/velesin/jasmine-jquery
7
+
8
+ Copyright (c) 2010-2014 Wojciech Zawistowski, Travis Jeffery
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining
11
+ a copy of this software and associated documentation files (the
12
+ "Software"), to deal in the Software without restriction, including
13
+ without limitation the rights to use, copy, modify, merge, publish,
14
+ distribute, sublicense, and/or sell copies of the Software, and to
15
+ permit persons to whom the Software is furnished to do so, subject to
16
+ the following conditions:
17
+
18
+ The above copyright notice and this permission notice shall be
19
+ included in all copies or substantial portions of the Software.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28
+ */
29
+
30
+(function (root, factory) {
31
+ if (typeof module !== 'undefined' && module.exports && typeof exports !== 'undefined') {
32
+ factory(root, root.jasmine, require('jquery'));
33
+ } else {
34
+ factory(root, root.jasmine, root.jQuery);
35
+ }
36
+}((function() {return this; })(), function (window, jasmine, $) { "use strict";
37
+
38
+ jasmine.spiedEventsKey = function (selector, eventName) {
39
+ return [$(selector).selector, eventName].toString()
40
+ }
41
+
42
+ jasmine.getFixtures = function () {
43
+ return jasmine.currentFixtures_ = jasmine.currentFixtures_ || new jasmine.Fixtures()
44
+ }
45
+
46
+ jasmine.getStyleFixtures = function () {
47
+ return jasmine.currentStyleFixtures_ = jasmine.currentStyleFixtures_ || new jasmine.StyleFixtures()
48
+ }
49
+
50
+ jasmine.Fixtures = function () {
51
+ this.containerId = 'jasmine-fixtures'
52
+ this.fixturesCache_ = {}
53
+ this.fixturesPath = 'spec/javascripts/fixtures'
54
+ }
55
+
56
+ jasmine.Fixtures.prototype.set = function (html) {
57
+ this.cleanUp()
58
+ return this.createContainer_(html)
59
+ }
60
+
61
+ jasmine.Fixtures.prototype.appendSet= function (html) {
62
+ this.addToContainer_(html)
63
+ }
64
+
65
+ jasmine.Fixtures.prototype.preload = function () {
66
+ this.read.apply(this, arguments)
67
+ }
68
+
69
+ jasmine.Fixtures.prototype.load = function () {
70
+ this.cleanUp()
71
+ this.createContainer_(this.read.apply(this, arguments))
72
+ }
73
+
74
+ jasmine.Fixtures.prototype.appendLoad = function () {
75
+ this.addToContainer_(this.read.apply(this, arguments))
76
+ }
77
+
78
+ jasmine.Fixtures.prototype.read = function () {
79
+ var htmlChunks = []
80
+ , fixtureUrls = arguments
81
+
82
+ for(var urlCount = fixtureUrls.length, urlIndex = 0; urlIndex < urlCount; urlIndex++) {
83
+ htmlChunks.push(this.getFixtureHtml_(fixtureUrls[urlIndex]))
84
+ }
85
+
86
+ return htmlChunks.join('')
87
+ }
88
+
89
+ jasmine.Fixtures.prototype.clearCache = function () {
90
+ this.fixturesCache_ = {}
91
+ }
92
+
93
+ jasmine.Fixtures.prototype.cleanUp = function () {
94
+ $('#' + this.containerId).remove()
95
+ }
96
+
97
+ jasmine.Fixtures.prototype.sandbox = function (attributes) {
98
+ var attributesToSet = attributes || {}
99
+ return $('<div id="sandbox" />').attr(attributesToSet)
100
+ }
101
+
102
+ jasmine.Fixtures.prototype.createContainer_ = function (html) {
103
+ var container = $('<div>')
104
+ .attr('id', this.containerId)
105
+ .html(html)
106
+
107
+ $(document.body).append(container)
108
+ return container
109
+ }
110
+
111
+ jasmine.Fixtures.prototype.addToContainer_ = function (html){
112
+ var container = $(document.body).find('#'+this.containerId).append(html)
113
+
114
+ if (!container.length) {
115
+ this.createContainer_(html)
116
+ }
117
+ }
118
+
119
+ jasmine.Fixtures.prototype.getFixtureHtml_ = function (url) {
120
+ if (typeof this.fixturesCache_[url] === 'undefined') {
121
+ this.loadFixtureIntoCache_(url)
122
+ }
123
+ return this.fixturesCache_[url]
124
+ }
125
+
126
+ jasmine.Fixtures.prototype.loadFixtureIntoCache_ = function (relativeUrl) {
127
+ var self = this
128
+ , url = this.makeFixtureUrl_(relativeUrl)
129
+ , htmlText = ''
130
+ , request = $.ajax({
131
+ async: false, // must be synchronous to guarantee that no tests are run before fixture is loaded
132
+ cache: false,
133
+ url: url,
134
+ dataType: 'html',
135
+ success: function (data, status, $xhr) {
136
+ htmlText = $xhr.responseText
137
+ }
138
+ }).fail(function ($xhr, status, err) {
139
+ throw new Error('Fixture could not be loaded: ' + url + ' (status: ' + status + ', message: ' + err.message + ')')
140
+ })
141
+
142
+ var scripts = $($.parseHTML(htmlText, true)).find('script[src]') || [];
143
+
144
+ scripts.each(function(){
145
+ $.ajax({
146
+ async: false, // must be synchronous to guarantee that no tests are run before fixture is loaded
147
+ cache: false,
148
+ dataType: 'script',
149
+ url: $(this).attr('src'),
150
+ success: function (data, status, $xhr) {
151
+ htmlText += '<script>' + $xhr.responseText + '</script>'
152
+ },
153
+ error: function ($xhr, status, err) {
154
+ throw new Error('Script could not be loaded: ' + url + ' (status: ' + status + ', message: ' + err.message + ')')
155
+ }
156
+ });
157
+ })
158
+
159
+ self.fixturesCache_[relativeUrl] = htmlText;
160
+ }
161
+
162
+ jasmine.Fixtures.prototype.makeFixtureUrl_ = function (relativeUrl){
163
+ return this.fixturesPath.match('/$') ? this.fixturesPath + relativeUrl : this.fixturesPath + '/' + relativeUrl
164
+ }
165
+
166
+ jasmine.Fixtures.prototype.proxyCallTo_ = function (methodName, passedArguments) {
167
+ return this[methodName].apply(this, passedArguments)
168
+ }
169
+
170
+
171
+ jasmine.StyleFixtures = function () {
172
+ this.fixturesCache_ = {}
173
+ this.fixturesNodes_ = []
174
+ this.fixturesPath = 'spec/javascripts/fixtures'
175
+ }
176
+
177
+ jasmine.StyleFixtures.prototype.set = function (css) {
178
+ this.cleanUp()
179
+ this.createStyle_(css)
180
+ }
181
+
182
+ jasmine.StyleFixtures.prototype.appendSet = function (css) {
183
+ this.createStyle_(css)
184
+ }
185
+
186
+ jasmine.StyleFixtures.prototype.preload = function () {
187
+ this.read_.apply(this, arguments)
188
+ }
189
+
190
+ jasmine.StyleFixtures.prototype.load = function () {
191
+ this.cleanUp()
192
+ this.createStyle_(this.read_.apply(this, arguments))
193
+ }
194
+
195
+ jasmine.StyleFixtures.prototype.appendLoad = function () {
196
+ this.createStyle_(this.read_.apply(this, arguments))
197
+ }
198
+
199
+ jasmine.StyleFixtures.prototype.cleanUp = function () {
200
+ while(this.fixturesNodes_.length) {
201
+ this.fixturesNodes_.pop().remove()
202
+ }
203
+ }
204
+
205
+ jasmine.StyleFixtures.prototype.createStyle_ = function (html) {
206
+ var styleText = $('<div></div>').html(html).text()
207
+ , style = $('<style>' + styleText + '</style>')
208
+
209
+ this.fixturesNodes_.push(style)
210
+ $('head').append(style)
211
+ }
212
+
213
+ jasmine.StyleFixtures.prototype.clearCache = jasmine.Fixtures.prototype.clearCache
214
+ jasmine.StyleFixtures.prototype.read_ = jasmine.Fixtures.prototype.read
215
+ jasmine.StyleFixtures.prototype.getFixtureHtml_ = jasmine.Fixtures.prototype.getFixtureHtml_
216
+ jasmine.StyleFixtures.prototype.loadFixtureIntoCache_ = jasmine.Fixtures.prototype.loadFixtureIntoCache_
217
+ jasmine.StyleFixtures.prototype.makeFixtureUrl_ = jasmine.Fixtures.prototype.makeFixtureUrl_
218
+ jasmine.StyleFixtures.prototype.proxyCallTo_ = jasmine.Fixtures.prototype.proxyCallTo_
219
+
220
+ jasmine.getJSONFixtures = function () {
221
+ return jasmine.currentJSONFixtures_ = jasmine.currentJSONFixtures_ || new jasmine.JSONFixtures()
222
+ }
223
+
224
+ jasmine.JSONFixtures = function () {
225
+ this.fixturesCache_ = {}
226
+ this.fixturesPath = 'spec/javascripts/fixtures/json'
227
+ }
228
+
229
+ jasmine.JSONFixtures.prototype.load = function () {
230
+ this.read.apply(this, arguments)
231
+ return this.fixturesCache_
232
+ }
233
+
234
+ jasmine.JSONFixtures.prototype.read = function () {
235
+ var fixtureUrls = arguments
236
+
237
+ for(var urlCount = fixtureUrls.length, urlIndex = 0; urlIndex < urlCount; urlIndex++) {
238
+ this.getFixtureData_(fixtureUrls[urlIndex])
239
+ }
240
+
241
+ return this.fixturesCache_
242
+ }
243
+
244
+ jasmine.JSONFixtures.prototype.clearCache = function () {
245
+ this.fixturesCache_ = {}
246
+ }
247
+
248
+ jasmine.JSONFixtures.prototype.getFixtureData_ = function (url) {
249
+ if (!this.fixturesCache_[url]) this.loadFixtureIntoCache_(url)
250
+ return this.fixturesCache_[url]
251
+ }
252
+
253
+ jasmine.JSONFixtures.prototype.loadFixtureIntoCache_ = function (relativeUrl) {
254
+ var self = this
255
+ , url = this.fixturesPath.match('/$') ? this.fixturesPath + relativeUrl : this.fixturesPath + '/' + relativeUrl
256
+
257
+ $.ajax({
258
+ async: false, // must be synchronous to guarantee that no tests are run before fixture is loaded
259
+ cache: false,
260
+ dataType: 'json',
261
+ url: url,
262
+ success: function (data) {
263
+ self.fixturesCache_[relativeUrl] = data
264
+ },
265
+ error: function ($xhr, status, err) {
266
+ throw new Error('JSONFixture could not be loaded: ' + url + ' (status: ' + status + ', message: ' + err.message + ')')
267
+ }
268
+ })
269
+ }
270
+
271
+ jasmine.JSONFixtures.prototype.proxyCallTo_ = function (methodName, passedArguments) {
272
+ return this[methodName].apply(this, passedArguments)
273
+ }
274
+
275
+ jasmine.jQuery = function () {}
276
+
277
+ jasmine.jQuery.browserTagCaseIndependentHtml = function (html) {
278
+ return $('<div/>').append(html).html()
279
+ }
280
+
281
+ jasmine.jQuery.elementToString = function (element) {
282
+ return $(element).map(function () { return this.outerHTML; }).toArray().join(', ')
283
+ }
284
+
285
+ var data = {
286
+ spiedEvents: {}
287
+ , handlers: []
288
+ }
289
+
290
+ jasmine.jQuery.events = {
291
+ spyOn: function (selector, eventName) {
292
+ var handler = function (e) {
293
+ var calls = (typeof data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] !== 'undefined') ? data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)].calls : 0
294
+ data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] = {
295
+ args: jasmine.util.argsToArray(arguments),
296
+ calls: ++calls
297
+ }
298
+ }
299
+
300
+ $(selector).on(eventName, handler)
301
+ data.handlers.push(handler)
302
+
303
+ return {
304
+ selector: selector,
305
+ eventName: eventName,
306
+ handler: handler,
307
+ reset: function (){
308
+ delete data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)]
309
+ },
310
+ calls: {
311
+ count: function () {
312
+ return data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] ?
313
+ data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)].calls : 0;
314
+ },
315
+ any: function () {
316
+ return data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] ?
317
+ !!data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)].calls : false;
318
+ }
319
+ }
320
+ }
321
+ },
322
+
323
+ args: function (selector, eventName) {
324
+ var actualArgs = data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)].args
325
+
326
+ if (!actualArgs) {
327
+ throw "There is no spy for " + eventName + " on " + selector.toString() + ". Make sure to create a spy using spyOnEvent."
328
+ }
329
+
330
+ return actualArgs
331
+ },
332
+
333
+ wasTriggered: function (selector, eventName) {
334
+ return !!(data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)])
335
+ },
336
+
337
+ wasTriggeredWith: function (selector, eventName, expectedArgs, util, customEqualityTesters) {
338
+ var actualArgs = jasmine.jQuery.events.args(selector, eventName).slice(1)
339
+
340
+ if (Object.prototype.toString.call(expectedArgs) !== '[object Array]')
341
+ actualArgs = actualArgs[0]
342
+
343
+ return util.equals(actualArgs, expectedArgs, customEqualityTesters)
344
+ },
345
+
346
+ wasPrevented: function (selector, eventName) {
347
+ var spiedEvent = data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)]
348
+ , args = (jasmine.util.isUndefined(spiedEvent)) ? {} : spiedEvent.args
349
+ , e = args ? args[0] : undefined
350
+
351
+ return e && e.isDefaultPrevented()
352
+ },
353
+
354
+ wasStopped: function (selector, eventName) {
355
+ var spiedEvent = data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)]
356
+ , args = (jasmine.util.isUndefined(spiedEvent)) ? {} : spiedEvent.args
357
+ , e = args ? args[0] : undefined
358
+
359
+ return e && e.isPropagationStopped()
360
+ },
361
+
362
+ cleanUp: function () {
363
+ data.spiedEvents = {}
364
+ data.handlers = []
365
+ }
366
+ }
367
+
368
+ var hasProperty = function (actualValue, expectedValue) {
369
+ if (expectedValue === undefined)
370
+ return actualValue !== undefined
371
+
372
+ return actualValue === expectedValue
373
+ }
374
+
375
+ beforeEach(function () {
376
+ jasmine.addMatchers({
377
+ toHaveClass: function () {
378
+ return {
379
+ compare: function (actual, className) {
380
+ return { pass: $(actual).hasClass(className) }
381
+ }
382
+ }
383
+ },
384
+
385
+ toHaveCss: function () {
386
+ return {
387
+ compare: function (actual, css) {
388
+ var stripCharsRegex = /[\s;\"\']/g
389
+ for (var prop in css) {
390
+ var value = css[prop]
391
+ // see issue #147 on gh
392
+ ;if ((value === 'auto') && ($(actual).get(0).style[prop] === 'auto')) continue
393
+ var actualStripped = $(actual).css(prop).replace(stripCharsRegex, '')
394
+ var valueStripped = value.replace(stripCharsRegex, '')
395
+ if (actualStripped !== valueStripped) return { pass: false }
396
+ }
397
+ return { pass: true }
398
+ }
399
+ }
400
+ },
401
+
402
+ toBeVisible: function () {
403
+ return {
404
+ compare: function (actual) {
405
+ return { pass: $(actual).is(':visible') }
406
+ }
407
+ }
408
+ },
409
+
410
+ toBeHidden: function () {
411
+ return {
412
+ compare: function (actual) {
413
+ return { pass: $(actual).is(':hidden') }
414
+ }
415
+ }
416
+ },
417
+
418
+ toBeSelected: function () {
419
+ return {
420
+ compare: function (actual) {
421
+ return { pass: $(actual).is(':selected') }
422
+ }
423
+ }
424
+ },
425
+
426
+ toBeChecked: function () {
427
+ return {
428
+ compare: function (actual) {
429
+ return { pass: $(actual).is(':checked') }
430
+ }
431
+ }
432
+ },
433
+
434
+ toBeEmpty: function () {
435
+ return {
436
+ compare: function (actual) {
437
+ return { pass: $(actual).is(':empty') }
438
+ }
439
+ }
440
+ },
441
+
442
+ toBeInDOM: function () {
443
+ return {
444
+ compare: function (actual) {
445
+ return { pass: $.contains(document.documentElement, $(actual)[0]) }
446
+ }
447
+ }
448
+ },
449
+
450
+ toExist: function () {
451
+ return {
452
+ compare: function (actual) {
453
+ return { pass: $(actual).length }
454
+ }
455
+ }
456
+ },
457
+
458
+ toHaveLength: function () {
459
+ return {
460
+ compare: function (actual, length) {
461
+ return { pass: $(actual).length === length }
462
+ }
463
+ }
464
+ },
465
+
466
+ toHaveAttr: function () {
467
+ return {
468
+ compare: function (actual, attributeName, expectedAttributeValue) {
469
+ return { pass: hasProperty($(actual).attr(attributeName), expectedAttributeValue) }
470
+ }
471
+ }
472
+ },
473
+
474
+ toHaveProp: function () {
475
+ return {
476
+ compare: function (actual, propertyName, expectedPropertyValue) {
477
+ return { pass: hasProperty($(actual).prop(propertyName), expectedPropertyValue) }
478
+ }
479
+ }
480
+ },
481
+
482
+ toHaveId: function () {
483
+ return {
484
+ compare: function (actual, id) {
485
+ return { pass: $(actual).attr('id') == id }
486
+ }
487
+ }
488
+ },
489
+
490
+ toHaveHtml: function () {
491
+ return {
492
+ compare: function (actual, html) {
493
+ return { pass: $(actual).html() == jasmine.jQuery.browserTagCaseIndependentHtml(html) }
494
+ }
495
+ }
496
+ },
497
+
498
+ toContainHtml: function () {
499
+ return {
500
+ compare: function (actual, html) {
501
+ var actualHtml = $(actual).html()
502
+ , expectedHtml = jasmine.jQuery.browserTagCaseIndependentHtml(html)
503
+
504
+ return { pass: (actualHtml.indexOf(expectedHtml) >= 0) }
505
+ }
506
+ }
507
+ },
508
+
509
+ toHaveText: function () {
510
+ return {
511
+ compare: function (actual, text) {
512
+ var actualText = $(actual).text()
513
+ var trimmedText = $.trim(actualText)
514
+
515
+ if (text && $.isFunction(text.test)) {
516
+ return { pass: text.test(actualText) || text.test(trimmedText) }
517
+ } else {
518
+ return { pass: (actualText == text || trimmedText == text) }
519
+ }
520
+ }
521
+ }
522
+ },
523
+
524
+ toContainText: function () {
525
+ return {
526
+ compare: function (actual, text) {
527
+ var trimmedText = $.trim($(actual).text())
528
+
529
+ if (text && $.isFunction(text.test)) {
530
+ return { pass: text.test(trimmedText) }
531
+ } else {
532
+ return { pass: trimmedText.indexOf(text) != -1 }
533
+ }
534
+ }
535
+ }
536
+ },
537
+
538
+ toHaveValue: function () {
539
+ return {
540
+ compare: function (actual, value) {
541
+ return { pass: $(actual).val() === value }
542
+ }
543
+ }
544
+ },
545
+
546
+ toHaveData: function () {
547
+ return {
548
+ compare: function (actual, key, expectedValue) {
549
+ return { pass: hasProperty($(actual).data(key), expectedValue) }
550
+ }
551
+ }
552
+ },
553
+
554
+ toContainElement: function () {
555
+ return {
556
+ compare: function (actual, selector) {
557
+ return { pass: $(actual).find(selector).length }
558
+ }
559
+ }
560
+ },
561
+
562
+ toBeMatchedBy: function () {
563
+ return {
564
+ compare: function (actual, selector) {
565
+ return { pass: $(actual).filter(selector).length }
566
+ }
567
+ }
568
+ },
569
+
570
+ toBeDisabled: function () {
571
+ return {
572
+ compare: function (actual, selector) {
573
+ return { pass: $(actual).is(':disabled') }
574
+ }
575
+ }
576
+ },
577
+
578
+ toBeFocused: function (selector) {
579
+ return {
580
+ compare: function (actual, selector) {
581
+ return { pass: $(actual)[0] === $(actual)[0].ownerDocument.activeElement }
582
+ }
583
+ }
584
+ },
585
+
586
+ toHandle: function () {
587
+ return {
588
+ compare: function (actual, event) {
589
+ if ( !actual || actual.length === 0 ) return { pass: false };
590
+ var events = $._data($(actual).get(0), "events")
591
+
592
+ if (!events || !event || typeof event !== "string") {
593
+ return { pass: false }
594
+ }
595
+
596
+ var namespaces = event.split(".")
597
+ , eventType = namespaces.shift()
598
+ , sortedNamespaces = namespaces.slice(0).sort()
599
+ , namespaceRegExp = new RegExp("(^|\\.)" + sortedNamespaces.join("\\.(?:.*\\.)?") + "(\\.|$)")
600
+
601
+ if (events[eventType] && namespaces.length) {
602
+ for (var i = 0; i < events[eventType].length; i++) {
603
+ var namespace = events[eventType][i].namespace
604
+
605
+ if (namespaceRegExp.test(namespace))
606
+ return { pass: true }
607
+ }
608
+ } else {
609
+ return { pass: (events[eventType] && events[eventType].length > 0) }
610
+ }
611
+
612
+ return { pass: false }
613
+ }
614
+ }
615
+ },
616
+
617
+ toHandleWith: function () {
618
+ return {
619
+ compare: function (actual, eventName, eventHandler) {
620
+ if ( !actual || actual.length === 0 ) return { pass: false };
621
+ var normalizedEventName = eventName.split('.')[0]
622
+ , stack = $._data($(actual).get(0), "events")[normalizedEventName]
623
+
624
+ for (var i = 0; i < stack.length; i++) {
625
+ if (stack[i].handler == eventHandler) return { pass: true }
626
+ }
627
+
628
+ return { pass: false }
629
+ }
630
+ }
631
+ },
632
+
633
+ toHaveBeenTriggeredOn: function () {
634
+ return {
635
+ compare: function (actual, selector) {
636
+ var result = { pass: jasmine.jQuery.events.wasTriggered(selector, actual) }
637
+
638
+ result.message = result.pass ?
639
+ "Expected event " + $(actual) + " not to have been triggered on " + selector :
640
+ "Expected event " + $(actual) + " to have been triggered on " + selector
641
+
642
+ return result;
643
+ }
644
+ }
645
+ },
646
+
647
+ toHaveBeenTriggered: function (){
648
+ return {
649
+ compare: function (actual) {
650
+ var eventName = actual.eventName
651
+ , selector = actual.selector
652
+ , result = { pass: jasmine.jQuery.events.wasTriggered(selector, eventName) }
653
+
654
+ result.message = result.pass ?
655
+ "Expected event " + eventName + " not to have been triggered on " + selector :
656
+ "Expected event " + eventName + " to have been triggered on " + selector
657
+
658
+ return result
659
+ }
660
+ }
661
+ },
662
+
663
+ toHaveBeenTriggeredOnAndWith: function (j$, customEqualityTesters) {
664
+ return {
665
+ compare: function (actual, selector, expectedArgs) {
666
+ var wasTriggered = jasmine.jQuery.events.wasTriggered(selector, actual)
667
+ , result = { pass: wasTriggered && jasmine.jQuery.events.wasTriggeredWith(selector, actual, expectedArgs, j$, customEqualityTesters) }
668
+
669
+ if (wasTriggered) {
670
+ var actualArgs = jasmine.jQuery.events.args(selector, actual, expectedArgs)[1]
671
+ result.message = result.pass ?
672
+ "Expected event " + actual + " not to have been triggered with " + jasmine.pp(expectedArgs) + " but it was triggered with " + jasmine.pp(actualArgs) :
673
+ "Expected event " + actual + " to have been triggered with " + jasmine.pp(expectedArgs) + " but it was triggered with " + jasmine.pp(actualArgs)
674
+
675
+ } else {
676
+ // todo check on this
677
+ result.message = result.pass ?
678
+ "Expected event " + actual + " not to have been triggered on " + selector :
679
+ "Expected event " + actual + " to have been triggered on " + selector
680
+ }
681
+
682
+ return result
683
+ }
684
+ }
685
+ },
686
+
687
+ toHaveBeenPreventedOn: function () {
688
+ return {
689
+ compare: function (actual, selector) {
690
+ var result = { pass: jasmine.jQuery.events.wasPrevented(selector, actual) }
691
+
692
+ result.message = result.pass ?
693
+ "Expected event " + actual + " not to have been prevented on " + selector :
694
+ "Expected event " + actual + " to have been prevented on " + selector
695
+
696
+ return result
697
+ }
698
+ }
699
+ },
700
+
701
+ toHaveBeenPrevented: function () {
702
+ return {
703
+ compare: function (actual) {
704
+ var eventName = actual.eventName
705
+ , selector = actual.selector
706
+ , result = { pass: jasmine.jQuery.events.wasPrevented(selector, eventName) }
707
+
708
+ result.message = result.pass ?
709
+ "Expected event " + eventName + " not to have been prevented on " + selector :
710
+ "Expected event " + eventName + " to have been prevented on " + selector
711
+
712
+ return result
713
+ }
714
+ }
715
+ },
716
+
717
+ toHaveBeenStoppedOn: function () {
718
+ return {
719
+ compare: function (actual, selector) {
720
+ var result = { pass: jasmine.jQuery.events.wasStopped(selector, actual) }
721
+
722
+ result.message = result.pass ?
723
+ "Expected event " + actual + " not to have been stopped on " + selector :
724
+ "Expected event " + actual + " to have been stopped on " + selector
725
+
726
+ return result;
727
+ }
728
+ }
729
+ },
730
+
731
+ toHaveBeenStopped: function () {
732
+ return {
733
+ compare: function (actual) {
734
+ var eventName = actual.eventName
735
+ , selector = actual.selector
736
+ , result = { pass: jasmine.jQuery.events.wasStopped(selector, eventName) }
737
+
738
+ result.message = result.pass ?
739
+ "Expected event " + eventName + " not to have been stopped on " + selector :
740
+ "Expected event " + eventName + " to have been stopped on " + selector
741
+
742
+ return result
743
+ }
744
+ }
745
+ }
746
+ })
747
+
748
+ jasmine.getEnv().addCustomEqualityTester(function(a, b) {
749
+ if (a && b) {
750
+ if (a instanceof $ || jasmine.isDomNode(a)) {
751
+ var $a = $(a)
752
+
753
+ if (b instanceof $)
754
+ return $a.length == b.length && $a.is(b)
755
+
756
+ return $a.is(b);
757
+ }
758
+
759
+ if (b instanceof $ || jasmine.isDomNode(b)) {
760
+ var $b = $(b)
761
+
762
+ if (a instanceof $)
763
+ return a.length == $b.length && $b.is(a)
764
+
765
+ return $b.is(a);
766
+ }
767
+ }
768
+ })
769
+
770
+ jasmine.getEnv().addCustomEqualityTester(function (a, b) {
771
+ if (a instanceof $ && b instanceof $ && a.size() == b.size())
772
+ return a.is(b)
773
+ })
774
+ })
775
+
776
+ afterEach(function () {
777
+ jasmine.getFixtures().cleanUp()
778
+ jasmine.getStyleFixtures().cleanUp()
779
+ jasmine.jQuery.events.cleanUp()
780
+ })
781
+
782
+ window.readFixtures = function () {
783
+ return jasmine.getFixtures().proxyCallTo_('read', arguments)
784
+ }
785
+
786
+ window.preloadFixtures = function () {
787
+ jasmine.getFixtures().proxyCallTo_('preload', arguments)
788
+ }
789
+
790
+ window.loadFixtures = function () {
791
+ jasmine.getFixtures().proxyCallTo_('load', arguments)
792
+ }
793
+
794
+ window.appendLoadFixtures = function () {
795
+ jasmine.getFixtures().proxyCallTo_('appendLoad', arguments)
796
+ }
797
+
798
+ window.setFixtures = function (html) {
799
+ return jasmine.getFixtures().proxyCallTo_('set', arguments)
800
+ }
801
+
802
+ window.appendSetFixtures = function () {
803
+ jasmine.getFixtures().proxyCallTo_('appendSet', arguments)
804
+ }
805
+
806
+ window.sandbox = function (attributes) {
807
+ return jasmine.getFixtures().sandbox(attributes)
808
+ }
809
+
810
+ window.spyOnEvent = function (selector, eventName) {
811
+ return jasmine.jQuery.events.spyOn(selector, eventName)
812
+ }
813
+
814
+ window.preloadStyleFixtures = function () {
815
+ jasmine.getStyleFixtures().proxyCallTo_('preload', arguments)
816
+ }
817
+
818
+ window.loadStyleFixtures = function () {
819
+ jasmine.getStyleFixtures().proxyCallTo_('load', arguments)
820
+ }
821
+
822
+ window.appendLoadStyleFixtures = function () {
823
+ jasmine.getStyleFixtures().proxyCallTo_('appendLoad', arguments)
824
+ }
825
+
826
+ window.setStyleFixtures = function (html) {
827
+ jasmine.getStyleFixtures().proxyCallTo_('set', arguments)
828
+ }
829
+
830
+ window.appendSetStyleFixtures = function (html) {
831
+ jasmine.getStyleFixtures().proxyCallTo_('appendSet', arguments)
832
+ }
833
+
834
+ window.loadJSONFixtures = function () {
835
+ return jasmine.getJSONFixtures().proxyCallTo_('load', arguments)
836
+ }
837
+
838
+ window.getJSONFixture = function (url) {
839
+ return jasmine.getJSONFixtures().proxyCallTo_('read', arguments)[url]
840
+ }
841
+}));