Jasmine Expected Spy to have been called

21,462

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.

Share:
21,462
Aj1
Author by

Aj1

BY-Day: I work as .Net/UI Developer.

Updated on August 20, 2020

Comments

  • Aj1
    Aj1 almost 4 years

    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.