【问题标题】:Typescript + jasmine.createSpy()打字稿 + jasmine.createSpy()
【发布时间】:2017-11-24 00:34:27
【问题描述】:

我正在使用 Typescript 为我的 Angular 项目编写单元测试

当我尝试为某些服务创建模拟时,我使用这种方式:

const serviceMock = <IMyService>{
    method: _.noop,
};

beforeEach(inject($injector => {
   testingService = new AccountingService(serviceMock);

   spyOn(serviceMock, 'method').and.callFake(()=>'hello');
 }

这工作正常 但是当我尝试使用jasmine.createSpy() 时,出现编译错误:

const serviceMock = <IMyService>{
    method: jasmine.createSpy('method').and.callFake(()=>'hello'),
};

Type '{ method: Spy;}' cannot be converted to type 'MyService'. Property 'getParams' is missing in type '{ method: Spy;}'.

但是getParamsMyService 的私有方法

我做错了什么?

【问题讨论】:

    标签: angular typescript unit-testing jasmine


    【解决方案1】:

    使用 Jasmine SpyObj&lt;T&gt; 已经定义和使用的类型。

    const serviceMock: jasmine.SpyObj<IMyService> = jasmine.createSpyObj<IMyService>('service',['method']);
    

    这样,IMyService 的每个方法都将被 Spy 增强:

    serviceMock.method.and.callFake(()=>'hello');
    

    【讨论】:

    • 我赞成很好地使用服务类型。应该使用jasmine.SpyObj&lt;IMyService&gt; 作为类型而不是IMyService
    【解决方案2】:

    用映射类型试试

    export type Spied<T> = {  
      [Method in keyof T]: jasmine.Spy;
    };
    

    并用它来模拟你的服务

    const serviceMock = Spied<IMyService>{
    

    查看here了解详细说明

    【讨论】:

      【解决方案3】:

      尝试使用 Partial 类型:

      const serviceMock = <Partial<IMyService>>{ 
      

      欲了解更多信息,请查看:https://www.typescriptlang.org/docs/handbook/advanced-types.html

      【讨论】:

      • 它没有帮助,但感谢您的 Partial 类型,这对我来说是新的
      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 2021-07-27
      • 1970-01-01
      • 2017-12-28
      • 2020-09-28
      • 2018-01-09
      • 2018-07-13
      • 2019-04-03
      相关资源
      最近更新 更多