被测代码:
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();
感谢瑞安的精彩回答!!