Documentation for http-client-mock


#1

We’ve read about aurelia-http-client-mock in the release notes for Early November 2017, but it seems the google-fu left us and we were unable to find the documentation for it. It would be great if someone could point me in the right direction.


#2

Yeah sorry at the moment I did that I ran our of time.
I’ll write a blog post about this soon and enhance the documentation :slight_smile:

Here is a complete example using the HttpClientMock and StageComponent.

import {HttpClientMock} from 'aurelia-http-client-mock';
import {reportUnfulfilled, reportUnexpected} from 'test/unit/report';
import {StageComponent} from 'aurelia-testing';
import {bootstrap} from 'aurelia-bootstrapper';


export function reportUnfulfilled(expect, httpMock) {
  let expectedUrls = httpMock.getExpected().map(stringifyXhr);
  expect(httpMock.isDone()).toBeTruthy(`Never called urls: \n${expectedUrls.join('\n')}`);
}

export function reportUnexpected(expect, httpMock) {
  let unexpectedUrls = httpMock.getUnexpected().map(stringifyXhr);
  expect(httpMock.hadUnexpected()).toBeFalsy(`Unexpected calls: \n${unexpectedUrls.join('\n')}`);
}

function stringifyXhr(xhr) {
  return `${xhr.method}: ${xhr.url}
    Sent ${stringifyHeaders(xhr.requestHeaders)}
        ${xhr.requestText || xhr.requestBody}
    Received ${stringifyHeaders(xhr.responseHeaders)}
        ${xhr.responseText || xhr.responseBody}`;
}

function stringifyHeaders(headers) {
  let keys = Object.keys(headers);
  let headerRepresentations = keys.map(key => `${key}: ${headers[key]}`);
  return keys.length ? `Headers ${headerRepresentations.join(' | ')}` : '';
}

describe('Overview', () => {
  let http;
  let component;
  let bindingContext;

  beforeEach(() => {
    bindingContext = {id: 1};
    http = new HttpClientMock();
    http.registerGlobally();

    component = StageComponent
      .withResources('app/view/entity/entity')
      .inView('<entity id.bind="id">')
      .boundTo(bindingContext);
  });

  afterEach(() => {
    reportUnfulfilled(expect, http);
    reportUnexpected(expect, http);
  });

  it('should load purchase orders', done => {
    http.expect('/backend/rest/api/entity')
      .withMethod('GET')
      .withRequestBody({id: bindingContext.id})
      .withResponseStatus(200)
      .withResponseHeader('Additional-header', 'one')
      .withResponseBody({crazy: 'entity'});
    
    component.create(bootstrap)
      .then(() => component.waitForElement('.entity-id'))
      .then(() => expect(component.element.querySelector('entity-id').textContent).toEqual('1'))
      .then(done)
      .catch(e => {
        fail(e.toString());
      });
  });

  afterEach(() => {
    component.dispose();
  });
});