代碼toHaveBeenCalled和toHaveBeenCalledWith正確報告茉莉spyOn沒有被測
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();
感謝瑞安的偉大的答案!
瑞恩 - 多好的回答!謝謝! – Mike