summaryrefslogtreecommitdiffstats
path: root/devtools/client/shared/test/shared-redux-head.js
blob: b0bbfc8172abd33b7d10e870e0d618a1c2cd6ea2 (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
/* Any copyright is dedicated to the Public Domain.
 * http://creativecommons.org/publicdomain/zero/1.0/ */

"use strict";

/* eslint no-unused-vars: [2, {"vars": "local"}] */
/* import-globals-from ./shared-head.js */

// Common utility functions for working with Redux stores.  The file is meant
// to be safe to load in both mochitest and xpcshell environments.

/**
 * Wait until the store has reached a state that matches the predicate.
 * @param Store store
 *        The Redux store being used.
 * @param function predicate
 *        A function that returns true when the store has reached the expected
 *        state.
 * @return Promise
 *         Resolved once the store reaches the expected state.
 */
function waitUntilState(store, predicate) {
  return new Promise(resolve => {
    const unsubscribe = store.subscribe(check);

    info(`Waiting for state predicate "${predicate}"`);
    function check() {
      if (predicate(store.getState())) {
        info(`Found state predicate "${predicate}"`);
        unsubscribe();
        resolve();
      }
    }

    // Fire the check immediately in case the action has already occurred
    check();
  });
}

/**
 * Wait until a particular action has been emitted by the store.
 * @param {Store} store
 *        The Redux store being used.
 * @param {String} actionType
 *        The expected action to wait for.
 * @param {Number} count
 *         Number of times to expect the action to occur. Default is once.
 * @return Promise
 *         Resolved once the expected action is emitted by the store.
 */
function waitUntilAction(store, actionType, count = 1) {
  return new Promise(resolve => {
    const unsubscribe = store.subscribe(check);
    const history = store.history;
    let index = history.length;

    info(`Waiting for action "${actionType}"`);
    function check() {
      const action = history[index++];
      if (action && action.type === actionType) {
        info(`Found action "${actionType}"`);
        count--;
        if (count === 0) {
          unsubscribe();
          resolve(store.getState());
        }
      }
    }
  });
}