UNPKG

2.33 kBJavaScriptView Raw
1import querystring from "querystring";
2
3class ResourceTestHelper {
4 static getRequestArgs(params, overrides = {}) {
5 var callsArgs = {
6 host: overrides.host || "api.nexmo.com",
7 path: overrides.path || "/v1/calls",
8 method: overrides.method || "POST",
9 body: overrides.hasOwnProperty("body")
10 ? overrides.body
11 : JSON.stringify(params),
12 headers: overrides.headers || {
13 "Content-Type": "application/json",
14 Authorization: "Bearer "
15 }
16 };
17
18 // Removed undefined properties
19 Object.keys(callsArgs).forEach(function(key) {
20 if (callsArgs[key] === undefined) {
21 delete callsArgs[key];
22 }
23 });
24
25 return callsArgs;
26 }
27
28 static requestArgsMatch(params, requestOverrides) {
29 return function(actual) {
30 var expected;
31 if (requestOverrides) {
32 expected = ResourceTestHelper.getRequestArgs(params, requestOverrides);
33 } else {
34 expected = params;
35 }
36
37 // We strip api_key and api_secret out of `path` so that our tests
38 // only look for specific parameters
39 var qs = actual.path.split("?");
40 var qsParts = querystring.parse(qs[1]);
41 delete qsParts["api_key"];
42 delete qsParts["api_secret"];
43 if (Object.keys(qsParts).length) {
44 actual.path = qs[0] + "?" + querystring.stringify(qsParts);
45 }
46
47 var match = true;
48
49 // Check response parameters
50 ["host", "path", "method", "body"].forEach(function(k) {
51 if (expected[k]) {
52 match = match && expected[k] == actual[k];
53 }
54 });
55
56 // Also check for any headers that we're expecting
57 expected.headers = expected.headers || {};
58 Object.keys(expected.headers).forEach(function(k) {
59 // We have a special check for authorization
60 if (k === "Authorization") {
61 return true;
62 }
63
64 match = match && expected.headers[k] === actual.headers[k];
65 });
66
67 // For Authorization we only check the beginning as JWTs are
68 // dynamically created
69 if (expected.headers["Authorization"]) {
70 match =
71 match &&
72 actual.headers["Authorization"].indexOf(
73 expected.headers["Authorization"]
74 ) === 0;
75 }
76
77 return match;
78 };
79 }
80}
81
82export default ResourceTestHelper;