Unit Test Breeze calls for Aurelia

411 views Asked by At

I have converted my fetch calls to use breeze.EntityQuery but how can I write my unit tests to mock the breeze client? Here is my code for the unit test fetch call that I'm trying to write for breeze.

class HttpStub {
    fetch(url) {
        var response = this.itemStub;
        this.url = url;
        return new Promise((resolve) => {
            resolve({ json: () => response });
        });
    }

    configure(func) {}
}

describe('Order', () => {
    var sut, http, itemStubs, itemFake;

    beforeEach(() => {
        http = new HttpStub();
        sut = new Order(http);
        itemStubs = [1];
        itemFake = [2];
        http.itemStub = itemStubs;
    });

    describe('getOrders', () => {
        it('should return orders', (done) => {
            var info = new Info("1", "C", null, null);
            sut.getOrders(info).then(result => {
                expect(result).toBe(itemStubs);
                expect(result).not.toBe(itemFake);
                done();
            });
        });
    });
});
1

There are 1 answers

0
Shaun Luttin On

Try using the jasmine spyOn function with callFake. Jasmine's spies are an easier way to mock a function call.

beforeEach(function () {
    spyOn(httpClient, "fetch").and.callFake(function () {
        return new Promise(function (resolve, reject) {
            var fetchResponse = "the fake response";
            resolve(fetchResponse);
        });
    });
});

An example (with TypeScript)

import { HttpClient } from "aurelia-fetch-client";
import { autoinject, Container } from "aurelia-framework";

@autoinject
export class DemoClass {

    constructor(private httpClient: HttpClient) { }

    public UseTheHttpClient() {
        return this.httpClient.fetch("some_url");
    }
}

describe("the demo class", function () {

    let container: Container = new Container();
    let httpClient: HttpClient = new HttpClient(); // create an http client
    container.registerInstance(HttpClient, httpClient);

    let demoClass: DemoClass = container.get(DemoClass);

    beforeEach(function () { // spy on that HTTP client
        spyOn(httpClient, "fetch").and.callFake(function () {
            return new Promise(function (resolve, reject) {
                resolve("some_fake_response");
            });
        });
    });

    it("returns the fake response", function (done) {
        demoClass.UseTheHttpClient().then((response) => {
            expect(response).toBe("some_fake_response");
            done();
        });
    });
});