aurelia / testing

Simplifies the testing of UI components by providing an elegant, fluent interface for arranging test setups along with a number of runtime debug/test helpers.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to mock a service using the HttpClient imported from 'aurelia-http-client'?

guidocecilio opened this issue · comments

How to mock a service using the HttpClient imported from 'aurelia-http-client'?

This is the service code:

import { inject } from 'aurelia-framework';
import { HttpClient } from 'aurelia-http-client';
import { Entity } from './../models/entity';

@inject(HttpClient)
export class EntityService {
  baseUrl = 'http://host/api/entities/';

  constructor(http) {
    this.http = http;
  }

  getEntities() {
    return new Promise((resolve, reject) => {
      this.http
        .configure(x => x.withBaseUrl(this.baseUrl))
        .get().then((httpResponse) => {
          let entities = JSON.parse(httpResponse.response).results;
          entities.forEach((entity) => {
            entity = Entity.fromObject(entity);
          });
          resolve(entities);
        }).catch( ( error ) => {
          reject(error);
        });
    });
  }

This is the test code:

import { EntityService } from '../../../src/services/entity-service';
import { Entity } from '../../../src/models/entity';
import { utils } from '../../../src/utils';

describe('the EntityService class', () => {
  let client, stub;

  beforeEach(() => {
    client = jasmine.createSpyObj('HttpClient', ['get']);
    stub = new EntityService(client);
  });

  function createEntity() {
    return Entity.fromObject({ uuid: utils.guid(), name: 'Test Entity'});
  }

  function createJsonResponseMock(content) {
    return Promise.resolve(content);
  }

  it('should fetch all entities', done => {
    const entities = [createEntity()];
    client.get.and.returnValue(Promise.resolve(entities));
    // FIXME:
    stub.getEntities()
      .then((result) => {
        expect(result).toEqual(entities)
      })
      .then(done);
  });
});

Is there any documentation available about http-client-mock?

Thanks a million in advance for all your support.

Please try asking this question in the Gitter channel or on Stack Overflow. Thanks!

I'll be honest, I kind of wish for an officially documented way to do this, preferably one that made it easy to have different app contexts, so you could easily test that a different user got different things, or different data resulted in a different view.