Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine Expected Spy to have been called

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.

like image 931
Aj1 Avatar asked Dec 24 '15 19:12

Aj1


1 Answers

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.

like image 88
Jorge Avatar answered Oct 14 '22 01:10

Jorge