aboutsummaryrefslogtreecommitdiffstats
path: root/helpers/FakeHttpProvider.js
blob: 0b01a171c6794c35ad04ee8c7a9a2cbbb7130764 (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
var chai = require('chai');
var assert = require('assert');
var utils = require('../../lib/utils/utils');

var getResponseStub = function () {
    return {
        jsonrpc: '2.0',
        id: 1,
        result: 0
    };
};

var FakeHttpProvider = function () {
    this.response = getResponseStub();
    this.error = null;
    this.validation = null;
};

FakeHttpProvider.prototype.send = function (payload) {
    assert.equal(utils.isArray(payload) || utils.isObject(payload), true);
    // TODO: validate jsonrpc request
    if (this.error) {
        throw this.error;
    } 
    if (this.validation) {
        // imitate plain json object
        this.validation(JSON.parse(JSON.stringify(payload)));
    }
    return this.getResponse();
};

FakeHttpProvider.prototype.sendAsync = function (payload, callback) {
    assert.equal(utils.isArray(payload) || utils.isObject(payload), true);
    assert.equal(utils.isFunction(callback), true);
    if (this.validation) {
        // imitate plain json object
        this.validation(JSON.parse(JSON.stringify(payload)), callback);
    }
    callback(this.error, this.getResponse());
};

FakeHttpProvider.prototype.injectResponse = function (response) {
    this.response = response;
};

FakeHttpProvider.prototype.injectResult = function (result) {
    this.response = getResponseStub();
    this.response.result = result;
};

FakeHttpProvider.prototype.injectBatchResults = function (results) {
    this.response = results.map(function (r) {
        var response = getResponseStub();
        response.result = r;
        return response;
    }); 
};

FakeHttpProvider.prototype.getResponse = function () {
    return this.response;
};

FakeHttpProvider.prototype.injectError = function (error) {
    this.error = error;
};

FakeHttpProvider.prototype.injectValidation = function (callback) {
    this.validation = callback;
};

module.exports = FakeHttpProvider;