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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With