All files / test/helpers mockiji_helpers.js

90.48% Statements 38/42
80% Branches 12/15
90% Functions 9/10
90.48% Lines 38/42
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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120    1x 1x   1x   1x 23x             23x   19x                 19x             19x 19x             23x   19x         19x 19x                   23x 60x                       23x 86x                 23x 21x 60x 60x 60x 60x   60x 60x 17x     60x 33x 33x     60x 3x 3x 3x           60x 14x 14x           21x      
'use strict';
 
const rp = require('request-promise-native');
const Mockiji = require('../../src/index');
 
const SERVER_PORT = 8081;
 
beforeEach(function() {
  this.serverInstance = null;
 
  /**
   * Start a new instance of Mockiji.
   * @param {string} dataPath - Path to the mock files
   * @return {Promise} A promise resolving on server startup
   */
  this.startServer = function({ dataPath, middlewares = [] }) {
    // Server configuration
    const configuration = {
      api_base_path: dataPath,
      port: this.getServerPort(),
      logs: [],
      silent: true,
      middlewares: middlewares,
    };
 
    // Check if the server is already running and stop it if that's the case
    Iif (this.serverInstance) {
      return this.stopServer().then(
        () => this.startServer({ dataPath })
      );
    }
 
    // Create a new Mockiji instance and start it
    this.serverInstance = new Mockiji({ configuration: configuration });
    return this.serverInstance.start();
  };
 
  /**
   * Stop the current Mockiji instance.
   * @return {Promise} A promise resolving on server shutdown
   */
  this.stopServer = function() {
    // If the server is already stopped
    Iif (!this.serverInstance) {
      return Promise.resolve();
    }
 
    // Stop the server
    return this.serverInstance.stop().then(() => {
      this.serverInstance = null;
    });
  };
 
  /**
   * Create and execute a new HTTP request.
   * @param {string} method - HTTP Method
   * @param {string} path - Path to use in the query
   * @return {Promise}
   */
  this.doRequest = function(method, path) {
    return rp({
      method: method,
      uri: `http://127.0.0.1:${this.getServerPort()}/${path}`,
      resolveWithFullResponse: true,
      simple: false,
    });
  }
 
  /**
   * Return the port Mockiji should be started on during tests.
   * @return {number}
   */
  this.getServerPort = function() {
    return SERVER_PORT;
  }
 
  /**
   * Test if the given query paths are using the right mock files.
   * @param {string} method - HTTP Method
   * @param {Object} paths - An object whose keys are query paths and values are expectations
   * @return {Promise}
   */
  this.checkPaths = function(method, paths) {
    const promises = Object.keys(paths).map((path) => {
      const expectedStatus = paths[path].status;
      const expectedFile = paths[path].file;
      const expectedResponse = paths[path].response;
      const expectedHeaders = paths[path].headers;
 
      return this.doRequest(method, path).then((response) => {
        if (expectedStatus) {
          expect(response.statusCode).toBe(expectedStatus, `Path "${path}" should return status code ${expectedStatus} but returned ${response.statusCode}`);
        }
 
        if (expectedFile) {
          const mockFile = response.headers['x-mockiji-file'];
          expect(mockFile.endsWith(expectedFile)).toBe(true, `Path "${path}" should use file "${expectedFile}" but used file "${mockFile}"`);
        }
 
        if (expectedResponse) {
          try {
            const serverResponse = (typeof expectedResponse === 'object') ? JSON.parse(response.body) : response.body;
            expect(serverResponse).toEqual(expectedResponse);
          } catch (e) {
            fail(`Server was expected to return a JSON response but returned "${response.body}"`);
          }
        }
 
        if (expectedHeaders) {
          for (let header in expectedHeaders) {
            expect(response.headers[header.toLowerCase()]).toEqual(expectedHeaders[header]);
          }
        }
      });
    });
 
    return Promise.all(promises);
  }
});