1 | import { vsprintf } from 'sprintf-js';
|
2 |
|
3 | module.exports = forEach;
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | function forEach(parameters, defaultIt = global.it) {
|
13 | const it = makeTestCaseDefiner(parameters, defaultIt);
|
14 | it.skip = makeParameterizedSkip(parameters, defaultIt);
|
15 | it.only = makeParameterizedOnly(parameters, defaultIt);
|
16 | return { it };
|
17 | }
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | function makeParameterizedSkip(parameters, defaultIt) {
|
25 | return makeTestCaseDefiner(
|
26 | parameters,
|
27 | defaultIt ? defaultIt.skip : undefined
|
28 | );
|
29 | }
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | function makeParameterizedOnly(parameters, defaultIt) {
|
36 | return function(title, test) {
|
37 | const it = makeTestCaseDefiner(parameters, defaultIt);
|
38 | global.describe.only('', () => it(title, test));
|
39 | };
|
40 | }
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 | function makeTestCaseDefiner(parameters, it) {
|
48 | return function defineTestCases(title, test) {
|
49 | const makeTitle = (typeof title === 'function')
|
50 | ? title
|
51 | : (...args) => vsprintf(title, args);
|
52 |
|
53 | const arrayParams = parameters.map(param => {
|
54 | return Array.isArray(param) ? param : [param];
|
55 | });
|
56 |
|
57 | const isAsync = isAsyncTest(arrayParams, test);
|
58 | arrayParams.forEach((param, index) => {
|
59 | it(
|
60 | makeTitle(...[...param, index]),
|
61 | makeTestBody(param, test, isAsync)
|
62 | );
|
63 | });
|
64 | };
|
65 | }
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 | function makeTestBody(param, test, isAsync) {
|
73 | if (isAsync) {
|
74 | return function(done) {
|
75 | test.apply(this, param.concat(done));
|
76 | };
|
77 | }
|
78 | return function() {
|
79 | test.apply(this, param);
|
80 | };
|
81 | }
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 | function isAsyncTest(parameters, test) {
|
88 | const nLongestParam = parameters.reduce((n, param) => {
|
89 | return Math.max(n, param.length);
|
90 | }, 0);
|
91 | return nLongestParam < test.length;
|
92 | }
|