forked from kfiron/node-fetch-response-matchers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (59 loc) · 1.83 KB
/
index.js
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
'use strict';
module.exports = (chai, utils) => {
require('./lib/status-methods')(method);
require('./lib/body-methods')(method);
require('./lib/header-methods')(method);
require('./lib/cookie-methods')(method);
require('./lib/cache-control-methods')(method);
function method(options) {
utils.addMethod(chai.Assertion.prototype, options.name, function () {
if (!utils.flag(this, 'promise')) {
var promise = buildBasedPromiseWithData(this._obj);
var derivedPromise = assert(promise, options, this, arguments);
utils.flag(this, 'promise', derivedPromise);
} else {
var promiseAssert = assert(utils.flag(this, 'promise'), options, this, arguments);
utils.flag(this, 'promise', promiseAssert);
}
if(options.name != 'afterwards'){
transferPromiseness(this, utils.flag(this, 'promise'));
}
});
}
function buildBasedPromiseWithData(obj){
var result = {};
var promise = fetchResult(obj, result);
return enrichBody(promise,
result);
}
function fetchResult(promise, result) {
return promise.then(response => {
result.response = response;
return result;
});
}
function enrichBody(promise, result) {
return promise.then(result => {
return result.response.buffer();
}).then(buffer => {
result.buffer = buffer;
result.text = buffer.toString();
return result;
});
}
function assert(promise, options, that, args) {
return promise.then(result => {
that.assert(
options.predicate(result, args),
options.msgSuccess(args),
options.msgFail(args),
options.expected(args),
options.actual(result)
);
return result;
})
}
function transferPromiseness(assertion, promise) {
assertion.then = promise.then.bind(promise);
}
};