'""' 类型的参数不能分配给 '"prototype"' jasmine 类型的参数

Wed*_*ada 2 jasmine angular

更新:

似乎以下作品:

let gaService = TestBed.get(GAService);
Run Code Online (Sandbox Code Playgroud)

并监视 gaService。

我对我在这里缺少的东西真的很空白。该服务将数据发送到谷歌分析,所以我必须在测试期间模拟它。服务本身是:

import { Injectable } from '@angular/core';
import { CoreService} from "./core.service";

@Injectable()
export class GAService {
  constructor(
    public coreService: CoreService
  ) { }

  public sendException (
    description: string,
    isFatal: boolean
  ) : Promise<any> {

    let promise = new Promise((resolve, reject) => {

      (<any>window).ga('send', 'exception', {
        'exDescription': description,
        'exFatal': isFatal
      });
    });

    return promise;
  }

}
Run Code Online (Sandbox Code Playgroud)

它被这样嘲笑:

import { Injectable } from "@angular/core";
@Injectable()
export class MockGAService {
  constructor() {}

  sendException(
    description: string,
    isFatal: boolean
  ): Promise<any> {
    return Promise.resolve(true);
  }

}
Run Code Online (Sandbox Code Playgroud)

现在在我的测试中,我有一个会引发异常的事件,我想确保确实调用了 sendException,所以我监视了这样的事件:

let preventDefaultSpy = spyOn(
  GAService,
  "sendException"
);
Run Code Online (Sandbox Code Playgroud)

但它根本不编译消息:

Argument of type '"sendException"' is not assignable to parameter of type '"prototype"'
Run Code Online (Sandbox Code Playgroud)

我让它编译的唯一方法是如果我这样做:

let preventDefaultSpy = spyOn(
  GAService.prototype,
  "sendException"
);
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时它永远不会被调用:

expect(preventDefaultSpy).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)

只是为了检查,我在模拟的 sendException() 上做了一个控制台输出,它显示了输出,暗示它确实被调用了。

我究竟做错了什么?

umi*_*der 5

JasminespyOn将间谍安装到现有对象上,但在您的示例中,您提供了一个类(第一个参数)。

let preventDefaultSpy = spyOn(GAService, "sendException").and.returnValue(Promise.resolve(true));
Run Code Online (Sandbox Code Playgroud)

因此,您的测试可以重写如下(不需要MockGAService):

const service = TestBed.get(GAService);
spyOn(service , "sendException").and.returnValue(Promise.resolve(true));

// do some stuff that is expected to invoke GAService.sendException

expect(service.sendException).toHaveBeenCalled();
Run Code Online (Sandbox Code Playgroud)