2

テスト中のコード:

module lib {
    export class Topic {
        private _callbacks: JQueryCallback;
        public id: string;
        public publish: any;
        public subscribe: any;
        public unsubscribe: any;
        public test: any;

        constructor(id: string) {
            this.id = id;
            this._callbacks = jQuery.Callbacks();
            this.publish = this._callbacks.fire;
            this.subscribe = this._callbacks.add;
            this.unsubscribe = this._callbacks.remove;
        }
    }

    export class Bus {
        private static _topics: Object = {};

        static topic(id: string): Topic {
            var topic = id && this._topics[id];

            if (!topic) {
                topic = new Topic(id);
                if (id) {
                    this._topics[id] = topic;
                }
            }

            return topic;
        }
    }
}

仕様テスト オブジェクト:

module lib {
    class Person {
        private _dfd: JQueryDeferred<Topic>;
        private _topic: Topic;

        constructor(public firstName: string) {
            this._dfd = jQuery.Deferred();
            this._topic = Bus.topic("user:logon");
            this._dfd.done(this._topic.publish);
        }

        logon() {
            this._dfd.resolve(this);
        }
    }

    class ApiService {
        constructor() {
            Bus.topic("user:logon").subscribe(this.callLogonApi);
        }
        callLogonApi(person: Person) {
            console.log("Person.firstname: " + person.firstName);
        }
    }

    describe("Bus", () => {
        var person: Person;
        var apiService: ApiService;

        beforeEach(() => {
            person = new Person("Michael");
            apiService = new ApiService();
            spyOn(apiService, "callLogonApi");

                //or this fails as well
                //spyOn(apiService, "callLogonApi").and.callThrough();
            person.logon();
        });

        it("should create subscription and catch the published event", () => {
            expect(apiService.callLogonApi).toHaveBeenCalled();

                //this fails too 
            //expect(apiService.callLogonApi).toHaveBeenCalledWith(person);
        });
    });
}

callLogonApi 関数が呼び出され、期待どおりにコンソールに書き込まれますが、出力は次のようになります。

Expected spy callLogonApi to have been called.
Error: Expected spy callLogonApi to have been called.

*これは、次のように変更された ApiService のコンストラクターで動作するようになりました。

    constructor() {
        Bus.topic("user:logon").subscribe((data)=> { this.callLogonApi(data); });
    }

*そして、spyOn が必要とします

        spyOn(apiService, "callLogonApi").and.callThrough();

ライアンのすばらしい答えに感謝します!!

4

1 に答える 1