The anticipated shock of Jasmine that was caused

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 does not work, saying that

 **Expected spy setSelectedCropYear to have been called. Error: Expected spy setSelectedCropYear to have been called.** 

I canโ€™t understand whatโ€™s wrong. Can someone tell me what is wrong with the test, please.

+7
source share
2 answers

The problem is that you are setting up a spy too late. By the time you connect the service spy, it has already been created and called setYear. But you obviously cannot mount a spy on a service until it is created.

One way to solve this problem is to monitor DataService.prototype.setYear. You can verify that it was called by a service instance by claiming that

Dataservice.prototype.setYear.calls.mostRecent().object is service.

+5
source

Fixed problem with 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); }); }); } 
0
source

Source: https://habr.com/ru/post/1239159/


All Articles