-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.js
88 lines (76 loc) · 2.77 KB
/
index.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
/*!
* data-driven
* Copyright(c) 2013 Fluent Software Solutions Ltd <[email protected]>
* MIT Licensed
*/
(function (global) {
/**
* Replaces all tokens in a given test title. This only supports Object lookups using dot notation.
*
* @param {Array} result Results from the RegExp.prototype.exec invocation
* @param {Object} testData The test data set from which we can extract values
* @param {String} title The original test title
* @return {String} The test title with all tokens replaced with their respective values
*/
function replaceTitleTokens(result, testData, title) {
var root = testData;
// Extract the value
result[1].split('.').forEach(function (key) {
root = root[key];
});
return title.replace(result[0], root);
}
function dataDriven(data, fn) {
var mochaIt = it;
var mochaBefore = before;
// Regex used to find tokens, e.g. {foo.bar}, {foo}
var re = /{([0-9a-zA-Z_$\._]+)}/g;
data.forEach(function(testData) {
try {
it = function(title, f) {
var result;
for (var key in testData) {
if (testData.hasOwnProperty(key)) {
while (result = re.exec(title)) {
title = replaceTitleTokens(result, testData, title);
}
}
}
if (f !== undefined) {
var testFn = f.length < 2 ?
function() {
return f.call(this,testData)
} :
function(done) {
return f.call(this,testData,done)
}
}
mochaIt(title, testFn);
};
before = function(f) {
var testFn = f.length < 2 ?
function() {
return f.call(this,testData)
} :
function(done) {
return f.call(this,testData,done)
}
mochaBefore(testFn);
};
fn();
} finally {
it = mochaIt;
before = mochaBefore;
}
})
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = dataDriven;
} else if (typeof define === 'function' && define.amd) {
define('data-driven', [], function () {
return dataDriven;
});
} else {
global.dataDriven = dataDriven;
}
})(this);