forked from marmelab/gremlins.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gizmo.js
82 lines (72 loc) · 2.43 KB
/
gizmo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Gizmo is a special mogwai who can stop the gremlins when they go too far
*
* The gizmo mogwai monitors the JavaScript alerts and the calls to
* console.alert(), and stops the stress test execution once the number of
* errors pass a certain threshold (10 errors by default).
*
* var gizmoMogwai = gremlins.mogwais.gizmo();
* horde.mogwai(gizmoMogwai);
*
* The gizmo mogwai can be customized as follows:
*
* gizmoMogwai.maxErrors(10); // the number of errors after which the test stops
* gizmoMogwai.logger(loggerObject); // inject a logger
*
* Example usage:
*
* horde.mogwai(gremlins.mogwais.gizmo()
* .maxErrors(5)
* );
*/
define(function(require) {
"use strict";
var configurable = require('../utils/configurable');
return function() {
/**
* @mixin
*/
var config = {
maxErrors: 10,
logger: null
};
var realOnError, realLoggerError;
/**
* @mixes config
*/
function gizmoMogwai() {
var nbErrors = 0;
var horde = this; // this is exceptional - don't use 'this' for mogwais in general
function incrementNbErrors() {
nbErrors++;
if (nbErrors == config.maxErrors) {
horde.stop();
if (!config.logger) return;
window.setTimeout(function() {
// display the mogwai error after the caught error
config.logger.warn('mogwai ', 'gizmo ', 'stopped test execution after ', config.maxErrors, 'errors');
}, 4);
}
}
// general JavaScript errors
realOnError = window.onerror;
window.onerror = function(message, url, linenumber) {
incrementNbErrors();
return realOnError ? realOnError(message, url, linenumber) : false;
};
// console errors
realLoggerError = console.error;
console.error = function() {
incrementNbErrors();
realLoggerError.apply(console, arguments);
};
}
gizmoMogwai.cleanUp = function() {
window.onerror = realOnError;
console.error = realLoggerError.bind(console);
return gizmoMogwai;
};
configurable(gizmoMogwai, config);
return gizmoMogwai;
};
});