import { module, test } from 'qunit';
import extractResponseErrorMessage from 'web-client/utilities/extract-response-error-message';

module('Unit | Utilities | extract-response-error-message');

test('given an object that looks like an Ember Data error', function(assert) {
  let response = {
    status: 400,
    responseJSON: {
      message: 'some message',
      status: 400
    }
  };

  assert.equal(
    extractResponseErrorMessage(response),
    'some message',
    "extracts the error's message"
  );
});

test('given an XMLHttpRequest ProgressEvent with a JSON message', function(assert) {
  let response = {
    target: {
      responseText: '{"message": "some message"}',
      status: 400
    }
  };

  assert.equal(
    extractResponseErrorMessage(response),
    'some message',
    "extracts the error's message"
  );
});

test('given an XMLHttpRequest ProgressEvent with a plain-text message', function(assert) {
  let response = {
    target: {
      responseText: 'some message',
      status: 400
    }
  };

  assert.equal(
    extractResponseErrorMessage(response),
    'some message',
    "extracts the error's message"
  );
});

test('given an XMLHttpRequest ProgressEvent with a 413 status code and error in statusText', function(assert) {
  let response = {
    target: {
      responseText: 'some message 1',
      statusText: 'some message 2',
      status: 413
    }
  };

  assert.equal(
    extractResponseErrorMessage(response),
    'some message 2',
    "extracts the error's message from statusText"
  );
});

test('given an 500 error with a message', function(assert) {
  let response = {
    status: 500,
    responseJSON: {
      message: 'some message',
      status: 500
    }
  };

  assert.equal(
    extractResponseErrorMessage(response),
    'some message',
    "extracts the error's message"
  );
});

test('given a 500 error without a message', function(assert) {
  let response = {
    status: 500
  };

  assert.equal(
    extractResponseErrorMessage(response),
    'Server error: 500',
    "provides a default error message"
  );
});
