1 | ;
|
2 |
|
3 | /**
|
4 | * This function will be stringified and then injected into every rewired module.
|
5 | *
|
6 | * Calling myModule.__with__("myPrivateVar", newValue) returns a function where
|
7 | * you can place your tests. As long as the returned function is executed variables
|
8 | * will be set to the given value, after that all changed variables are reset back to normal.
|
9 | *
|
10 | * @param {String|Object} varName name of the variable to set
|
11 | * @param {String} varValue new value
|
12 | * @return {Function}
|
13 | */
|
14 | function __with__() {
|
15 | var args = arguments;
|
16 |
|
17 | return function (callback) {
|
18 | var undo,
|
19 | returned,
|
20 | isPromise;
|
21 |
|
22 | if (typeof callback !== "function") {
|
23 | throw new TypeError("__with__ expects a callback function");
|
24 | }
|
25 |
|
26 | undo = module.exports.__set__.apply(null, args);
|
27 |
|
28 | try {
|
29 | returned = callback();
|
30 | isPromise = returned && typeof returned.then === "function";
|
31 | if (isPromise) {
|
32 | returned.then(undo, undo);
|
33 | return returned;
|
34 | }
|
35 | } finally {
|
36 | if (!isPromise) {
|
37 | undo();
|
38 | }
|
39 | }
|
40 | };
|
41 | }
|
42 |
|
43 | module.exports = __with__; |
\ | No newline at end of file |