这是我的角色工厂,用打字稿写成:
export class DataService {
constructor () {
this.setYear(2015);
}
setYear = (year:number) => {
this._selectedYear =year;
}
}
这是我的测试文件。
import {DataService } from ' ./sharedData.Service';
export function main() {
describe("DataService", () => {
let service: DataService;
beforeEach(function () {
service = new DataService();
});
it("should initialize shared data service", () => {
spyOn(service, "setYear");
expect(service).toBeDefined();
expect(service.setYear).toHaveBeenCalled(2015);
});
});
}
当我运行文件时,测试失败说
**Expected spy setSelectedCropYear to have been called.
Error: Expected spy setSelectedCropYear to have been called.**
我无法弄清楚出了什么问题。任何人都可以告诉我测试有什么问题。
答案 0 :(得分:3)
问题是你设置间谍太晚了。当您将间谍安装到服务上时,它已经被构造并且已经调用了setYear。但是你显然无法在构造之前将间谍装上服务。解决这个问题的一种方法是监视DataService.prototype.setYear。您可以确保服务实例调用它,声明Dataservice.prototype.setYear.calls.mostRecent()。object是service。
答案 1 :(得分:0)
修正了此处的问题是更新后的测试。
import {DataService } from ' ./sharedData.Service';
export function main() {
describe("DataService", () => {
let service: DataService;
beforeEach(function () {
service = new DataService();
});
it("should initialize shared data service", () => {
var spy = spyOn(service, "setYear").and.callThrough();
expect(service).toBeDefined();
expect(spy);
expect(service._selectedYear).toEqual(2015);
});
});
}