typescript 茉莉花预计间谍已被调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34457386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:10:45  来源:igfitidea点击:

Jasmine Expected Spy to have been called

angularjstypescriptjasminekarma-jasmine

提问by Aj1

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.

我无法弄清楚出了什么问题。谁能告诉我测试有什么问题。

回答by Jorge

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.

问题是你设置间谍太晚了。当您安装间谍服务时,它已经被构建并且 setYear 已经被调用。但是您显然不能在服务构建之前安装间谍服务。

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。您可以确保它是由服务实例调用的,断言

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

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

回答by Aj1

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);
        });
    });
}