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

import { expect } from 'chai';
import { check, failFast } from './ipc-helpers';

export class IpcChain {
  _expectedCalls: Array<string>;
  _recordedCalls: Array<string>;
  _mockIpc: {};
  _done: (*) => void;

  constructor(mockIpc: {}, done: (*) => void) {
    this._expectedCalls = [];
    this._recordedCalls = [];
    this._mockIpc = mockIpc;
    this._done = done;
  }

  addRequiredStep(ipcCall: string): StepBuilder {
    this._expectedCalls.push(ipcCall);
    return new StepBuilder(ipcCall, this._addStep.bind(this));
  }

  _addStep(step: StepBuilder) {
    const me = this;
    this._mockIpc[step.ipcCall] = function() {
      return new Promise(r => me._stepPromiseCallback(step, r, arguments));
    };
  }

  _stepPromiseCallback(step, resolve, args) {
    this._registerCall(step.ipcCall);

    if (step.inputValidation) {
      failFast(() => step.inputValidation(...args), this._done);
    }

    if (this._isLastCall()) {
      this._ensureChainCalledCorrectly();
    }

    resolve(step.returnValue);
  }

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

class StepBuilder {
  ipcCall: string;
  inputValidation: () => void;
  returnValue: *;
  _cb: (StepBuilder) => void;

  constructor(ipcCall: string, cb: (StepBuilder)=> void) {
    this.ipcCall = ipcCall;
    this._cb = cb;
  }

  withInputValidation(iv: () => void): StepBuilder {
    this.inputValidation = iv;
    return this;
  }

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

  done() {
    this._cb(this);
  }
}