Reputation: 973
Here is my angular factory written in typescript:
export class DataService {
constructor () {
this.setYear(2015);
}
setYear = (year:number) => {
this._selectedYear =year;
}
}
Here is my test file.
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);
});
});
}
When I run the file the test failing saying that
**Expected spy setSelectedCropYear to have been called.
Error: Expected spy setSelectedCropYear to have been called.**
I am not able to figure what is wrong. Can anyone tell me what is wrong with the test please.
Upvotes: 8
Views: 23932
Reputation: 81
The problem is you are setting up the spy too late. By the time you mount the spy on service, it has already been constructed and setYear has been called. But you obviously can not mount the spy on service before it is constructed.
One way around this is to spy on DataService.prototype.setYear. You can make sure it was called by the service instance asserting that
Dataservice.prototype.setYear.calls.mostRecent().object is service.
Upvotes: 8
Reputation: 973
Fixed the issue here is the updated Test.
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);
});
});
}
Upvotes: 0