Skip to content

Instantly share code, notes, and snippets.

@JoshuaVSherman
Last active January 21, 2017 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaVSherman/454704d7fc3fa2fa407263fd8c4aa1ee to your computer and use it in GitHub Desktop.
Save JoshuaVSherman/454704d7fc3fa2fa407263fd8c4aa1ee to your computer and use it in GitHub Desktop.
How to Unit Test a Function that Overwrites an Aurelia Component

To cover this particular function one needs to call app.configHttpClient() either directly, or by calling app.activate().

The httpClient is aurelia's fetch wrapper (docs: http://aurelia.io/hub.html#/doc/article/aurelia/fetch-client/latest/http-services/2) which is initialized in the App's constructor.

By default it's @injected by aurelia


import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';

@inject(Router, FetchConfig, AuthService, AppRouterConfig, HttpClient)
export class App {
  constructor(router, fetchConfig, auth, appRouterConfig, httpClient){
    this.router = router;
    
    this.httpClient = httpClient;
  }

but in the test (app.spec.js) it's stubbed with a class HttpStub in beforeEach.

class HttpStub { configure(){} }

  beforeEach(() => {
    app1 = new App(null, null, new AuthStub(), new RouterStub(), new HttpStub());

The configure function in this stub can then validate the function passed to it (httpConfig => { httpConfig…), whcih is exactly what I've done:

it('tests configHttpClient', () => {
  app1.configHttpClient();
  app1.httpClient.__configureCallback(new (class {
    withDefaults() {return this}
    withInterceptor() {return this}
  })())
});

Here the httpClient.__configureCallback was defined to store the callback passed to httpClient.configure when called in the stub:

class HttpStub {
  configure(fn) {
    this.__configureCallback = fn
    return this.__configureReturns;
  }

Gist provided by Freeth Lua

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment