aboutsummaryrefslogtreecommitdiffstats
path: root/packages/dev-utils/src/callback_error_reporter.ts
blob: 8432bb5d46feaebd3c0d6e634cb4a7d9f87aaeac (plain) (blame)
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 * as chai from 'chai';
import * as _ from 'lodash';

import { DoneCallback } from '@0xproject/types';

const expect = chai.expect;

export const callbackErrorReporter = {
    reportNoErrorCallbackErrors(
        done: DoneCallback,
        expectToBeCalledOnce: boolean = true,
    ): <T>(f?: ((value: T) => void) | undefined) => (value: T) => void {
        const callback = <T>(f?: (value: T) => void) => {
            const wrapped = (value: T) => {
                if (_.isUndefined(f)) {
                    done();
                    return;
                }
                try {
                    f(value);
                    if (expectToBeCalledOnce) {
                        done();
                    }
                } catch (err) {
                    done(err);
                }
            };
            return wrapped;
        };
        return callback;
    },
    reportNodeCallbackErrors(
        done: DoneCallback,
        expectToBeCalledOnce: boolean = true,
    ): <T>(f?: ((value: T) => void) | undefined) => (error: Error | null, value: T | undefined) => void {
        const callback = <T>(f?: (value: T) => void) => {
            const wrapped = (error: Error | null, value: T | undefined) => {
                if (!_.isNull(error)) {
                    done(error);
                } else {
                    if (_.isUndefined(f)) {
                        done();
                        return;
                    }
                    try {
                        f(value as T);
                        if (expectToBeCalledOnce) {
                            done();
                        }
                    } catch (err) {
                        done(err);
                    }
                }
            };
            return wrapped;
        };
        return callback;
    },
    assertNodeCallbackError(
        done: DoneCallback,
        errMsg: string,
    ): <T>(error: Error | null, value: T | undefined) => void {
        const wrapped = <T>(error: Error | null, value: T | undefined) => {
            if (_.isNull(error)) {
                done(new Error('Expected callback to receive an error'));
            } else {
                try {
                    expect(error.message).to.be.equal(errMsg);
                    done();
                } catch (err) {
                    done(err);
                }
            }
        };
        return wrapped;
    },
};