summaryrefslogtreecommitdiffhomepage
path: root/test/helpers/IpcChain.js
blob: 1505621cc062380249a11b9ae34f928078877f16 (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
// @flow

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;
  }

  expect<R>(ipcCall: string): StepBuilder<R> {
    const builder = new StepBuilder(ipcCall);
    this._expectedCalls.push(ipcCall);
    this._addStep(builder);

    return builder;
  }

  _addStep<R>(step: StepBuilder<R>) {
    this._mockIpc[step.ipcCall] = (...args: Array<mixed>) => {
      return new Promise((r) => this._stepPromiseCallback(step, r, args));
    };
  }

  _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: ?(...args: Array<mixed>) => void;
  returnValue: ?R;

  constructor(ipcCall: string) {
    this.ipcCall = ipcCall;
  }

  withInputValidation(iv: (...args: Array<mixed>) => void): this {
    this.inputValidation = iv;
    return this;
  }

  withReturnValue(rv: R): this {
    this.returnValue = rv;
    return this;
  }
}