summaryrefslogtreecommitdiffstats
path: root/js/dav/test/unit/nock_wrapper.js
blob: f665a0eae9f122c6be699a1a65eac847dcc45e58 (plain)
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
/**
 * @fileoverview Decorates nock with some useful utilities.
 */
import { assert } from 'chai';
import co from 'co';
import nock from 'nock';

export function nockWrapper(url) {
  let result = nock(url);

  // This is a hack suggested here https://github.com/pgte/nock#protip
  // to intercept the request conditional on the request body.
  result.matchRequestBody = (path, method, match, options={}) => {
    let statusCode = options.statusCode || 200;
    let statusText = options.statusText || '200 OK';
    return result
      .filteringRequestBody(body => match(body) ? '*' : '')
      .intercept(path, method, '*')
      .delay(1)
      .reply(statusCode, statusText);
  };

  /**
   * Whether or not an error is thrown in the promise,
   * the mock should have intercepted the request.
   */
  result.verify = co.wrap(function *(promise) {
    try {
      yield promise;
    } catch (error) {
      assert.notInclude(error.toString(), 'ECONNREFUSED');
    } finally {
      result.done();
    }
  });

  return result;
}

Object.keys(nock).forEach(key => {
  let value = nock[key];
  if (typeof value !== 'function') {
    return;
  }

  nockWrapper[key] = value.bind(nockWrapper)
});