-
Notifications
You must be signed in to change notification settings - Fork 6
/
jasmine2-custom-message.js
95 lines (82 loc) · 2.66 KB
/
jasmine2-custom-message.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
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
* jasmine2-custom-message
* https://github.com/avrelian/jasmine2-custom-message
*
* Copyright (c) 2014 Sergey Radchenko
* Licensed under the MIT license.
*/
(function(global) {
'use strict';
if (! (global.jasmine && global.expect)) {
return;
}
var ofType = function(val) {
var types = [].slice.call(arguments, 1);
var valType = val === null ? 'null' : typeof val;
return types.indexOf(valType) > -1;
};
var formatString = function(data, message) {
if (
(
data.matcherName === "toHaveBeenCalled" ||
data.matcherName === "toHaveBeenCalledTimes"
) &&
data.actual &&
data.actual.calls &&
typeof data.actual.calls.count === 'function'
) {
message = message.replace(/#\{actual\}/g, data.actual.calls.count());
} else {
message = message.replace(/#\{actual\}/g, data.actual);
}
message = message.replace(/#\{expected\}/g, data.expected);
message = message.replace(/#\{message\}/g, data.message);
return message;
};
var getMessage = function(data, message) {
while (! ofType(message, 'string', 'number', 'boolean')) {
switch (true) {
case ofType(message, 'undefined', 'null'):
message = data.message || 'You cannot use `' + message + '` as a custom message';
break;
case ofType(message, 'function'):
message = message.call(data);
break;
case message && ofType(message.toString, 'function') && message.toString().indexOf('[object ') !== 0:
message = message.toString();
break;
case JSON && ofType(JSON.stringify, 'function'):
message = JSON.stringify(message);
break;
default:
message = 'N/A';
}
}
if (ofType(message, 'string')) {
return formatString(data, message);
}
return message.toString();
};
var wrapAddExpectationResult = function(addExpectationResult, customMessage) {
return function(passed, data) {
data.message = getMessage(data, customMessage);
addExpectationResult(passed, data);
};
};
var wrapExpect = function(expect, customMessage) {
return function(actual) {
var assertion = expect(actual);
assertion.addExpectationResult = assertion.not.addExpectationResult = wrapAddExpectationResult(assertion.addExpectationResult, customMessage);
return assertion;
};
};
global.since = function(customMessage) {
return {
expect: wrapExpect(global.expect, customMessage)
};
};
if (typeof module !== 'undefined' && typeof module.exports === 'object') {
module.exports = global.since;
}
return global.since;
})((function(){return this;})());