首页 > 解决方案 > Angular Karma/Jesmine spyOn 创建类型“x”不能分配给“从不”类型的参数

问题描述

我在下面有一个常量类。当我尝试使用 spyOn 返回不同的值以测试错误情况时,ng test 返回编译时错误类型的参数'"retryCount"' is not assignable to parameter of type 'never'.

有没有办法解决这个问题?

 export class NConstants {
  public static retryCount: number = 2;
  public static readonly retryDelayInMilliseconds: number = 10000; // ms
  public static readonly retryNotificationDelayInSeconds: number = 50;
}


spyOn(NetworkConstants, 'retryCount').and.returnValue(0);

所有套餐

    "jasmine-auto-spies": "^4.1.0",
    "jasmine-core": "~3.3.0",
    "jasmine-marbles": "^0.6.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^3.1.3",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "^2.0.0",
    "karma-coverage-istanbul-reporter": "^2.0.4",
    "karma-firefox-launcher": "^1.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "karma-trx-reporter": "^0.3.0",

标签: angularkarma-jasminekarma-runner

解决方案


您只能spyOn使用类的方法/函数,而不是实例变量。

要改成返回0,直接修改即可。

NConstants.retryCount = 0;
// do what you want.
// further down the line, you can reset it
NConstants.retryCounter = 2;

推荐阅读