Unit Test Breeze呼唤Aurelia

时间:2016-08-05 19:59:53

标签: jasmine breeze aurelia aurelia-breeze

我已将我的fetch调用转换为使用breeze.EntityQuery但是如何编写单元测试以模拟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 个答案:

答案 0 :(得分:2)

尝试将spyOn函数与callFake一起使用。 Jasmine's spies是一种模拟函数调用的简单方法。

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

示例(使用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();
        });
    });
});