-
Notifications
You must be signed in to change notification settings - Fork 17
/
index.js
77 lines (66 loc) · 2.27 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
import { Mongo } from 'meteor/mongo';
import { Random } from 'meteor/random';
import sinon from 'sinon';
const StubCollections = (() => {
const publicApi = {};
const privateApi = {};
/* Public API */
publicApi.add = (collections) => {
privateApi.collections = privateApi.collections.concat(collections);
};
publicApi.stub = (collections) => {
const pendingCollections = collections || privateApi.collections;
[].concat(pendingCollections).forEach((collection) => {
if (!privateApi.pairs.has(collection)) {
const options = {
connection: null,
transform: collection._transform,
};
const localCollection = new collection.constructor(collection._name, options);
privateApi.stubPair({ localCollection, collection });
privateApi.pairs.set(collection, localCollection);
}
});
};
publicApi.restore = () => {
// Pre-emptively remove the documents from the local collection because if
// a collection with the same name is stubbed later it will still have the
// documents from LocalConnectionDriver's internal cache.
for (const localCollection of privateApi.pairs.values()) {
localCollection.remove({});
}
privateApi.sandbox.restore();
privateApi.pairs.clear();
};
/* Private API */
privateApi.sandbox = sinon.createSandbox();
privateApi.pairs = new Map();
privateApi.collections = [];
privateApi.symbols = Object.keys(Mongo.Collection.prototype);
privateApi.assignLocalFunctionsToReal = (local, real) => {
privateApi.symbols.forEach((symbol) => {
if (symbol === 'simpleSchema') return;
if (typeof local[symbol] !== 'function') return;
if (typeof real[symbol] !== 'function') return;
privateApi.sandbox.stub(real, symbol).callsFake(
local[symbol].bind(local),
);
});
};
privateApi.stubPair = (pair) => {
privateApi.assignLocalFunctionsToReal(
pair.localCollection,
pair.collection,
);
// If using `matb33:collection-hooks`, make sure direct functions are also
// stubbed.
if (pair.collection.direct) {
privateApi.assignLocalFunctionsToReal(
pair.localCollection,
pair.collection.direct,
);
}
};
return publicApi;
})();
export default StubCollections;