aboutsummaryrefslogtreecommitdiffstats
path: root/packages/dev-utils/src/callback_error_reporter.ts
blob: c8e6936737eadd58be26c15958b2caf501fe494c (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
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 = true) {
        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 = true) {
        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) {
        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;
    },
};