blob: 4e3ddea79ede669a2f7cb93c5335349d39ab4367 (
plain)
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
96
97
98
99
100
101
102
103
104
105
|
// @flow
import { expect } from 'chai';
import { check, failFast } from './ipc-helpers';
export class IpcChain {
_expectedCalls: Array<string>;
_recordedCalls: Array<string>;
_mockIpc: {};
_done: (?Error) => void;
_aborted: boolean;
constructor(mockIpc: {}) {
this._expectedCalls = [];
this._recordedCalls = [];
this._mockIpc = mockIpc;
this._aborted = false;
}
require<R>(ipcCall: string): StepBuilder<R> {
this._expectedCalls.push(ipcCall);
return new StepBuilder(ipcCall, this._addStep.bind(this));
}
_addStep<R>(step: StepBuilder<R>) {
const me = this;
this._mockIpc[step.ipcCall] = function() {
return new Promise(r => me._stepPromiseCallback(step, r, arguments));
};
}
_stepPromiseCallback<R>(step: StepBuilder<R>, resolve: (?R) => void, args: Array<mixed>) {
if (this._aborted) {
return;
}
this._registerCall(step.ipcCall);
const inputValidation = step.inputValidation;
if (inputValidation) {
const failedInputValidation = failFast(() => {
inputValidation(...args);
}, this._done);
if (failedInputValidation) {
this._abort();
return;
}
}
if (this._isLastCall()) {
this._ensureChainCalledCorrectly();
}
resolve(step.returnValue);
}
_abort() {
this._aborted = true;
}
_isLastCall(): boolean {
return this._recordedCalls.length === this._expectedCalls.length;
}
_ensureChainCalledCorrectly() {
check(() => {
expect(this._expectedCalls).to.deep.equal(this._recordedCalls);
}, this._done);
}
_registerCall(ipcCall: string) {
this._recordedCalls.push(ipcCall);
}
onSuccessOrFailure(done: (*) => void) {
this._done = done;
}
}
class StepBuilder<R> {
ipcCall: string;
inputValidation: ?() => void;
returnValue: ?R;
_cb: (StepBuilder<R>) => void;
constructor(ipcCall: string, cb: (StepBuilder<R>) => void) {
this.ipcCall = ipcCall;
this._cb = cb;
}
withInputValidation(iv: () => void): this {
this.inputValidation = iv;
return this;
}
withReturnValue(rv: R): this {
this.returnValue = rv;
return this;
}
done() {
this._cb(this);
}
}
|