【问题标题】:Jasmine - how to unit test a TypeScript class that imports another class with static methodsJasmine - 如何对使用静态方法导入另一个类的 TypeScript 类进行单元测试
【发布时间】:2017-09-12 00:26:22
【问题描述】:

我有一个简单的 TypeScript 类(在我的 Ionic 应用程序中),它实现了一个简单的“类型化”字典...

import { Utils } from './utils';

 export class Dictionary<T> {
   constructor(private noCase?: boolean, init?: Array<{ key: string; value:T; }>) {
    ....
   }
}

我已经为它写了一些非常简单的测试......

    import { Dictionary } from './dictionary';

    let dictionary : Dictionary<string> = null;
    describe('Dictionary', () => {
         beforeEach(() => {
            dictionary = new Dictionary<string>(true, []);
        });

      it('should have containsKey find a value added', () => {
          dictionary.add("a", "A Val");
          let exists = dictionary.containsKey("a");
          expect(exists).toBeTruthy()
         });
    });

当我运行测试时,我收到以下错误...

        Chrome 60.0.3112 (Windows 10 0.0.0) ERROR
      Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_3__dictionary__.a is not a constructor
      at webpack:///src/shared/utils.ts:19:17 <- test-config/karma-test-shim.js:77758
    Chrome 60.0.3112 (Windows 10 0.0.0) ERROR
      Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_3__dictionary__.a is not a constructor
      at webpack:///src/shared/utils.ts:19:17 <- test-config/karma-test-shim.js:77758
    Chrome 60.0.3112 (Windows 10 0.0.0): Executed 0 of 0 ERROR (0.422 secs / 0 secs)
    webpack: Compiling...

我的问题是我在正在测试的课程中的Utils 课程(Dictionary

这个Utils 类只有一堆静态“utils”方法,(字符串比较、格式化等)

    import * as moment from 'moment';
    import 'moment-duration-format';
    import * as _ from 'lodash';
    import { TranslateService } from 'ng2-translate';
    import { Dictionary } from './dictionary';
    .....


    export class Utils {
      public static guard(obj: any, name: string): void {
        if (obj == null || obj == undefined)
          throw (name + " must not be null!");
      }

       public static guardS(s: string, name: string): void {
        if (this.isNullorEmptyOrWhiteSpace(s))
          throw (name + " must not be null or empty!");
       }

      ...  etc
      }

我在UtilsDictionary 类中使用的唯一方法是静态guard 方法(如上所示)。

有没有一种方法可以测试我的类,该类使用静态方法包含这个其他类?我可以模拟这个类的静态方法吗?

虽然上面的类是微不足道的,但我还有其他东西想测试,其中还包括这个静态的Utils 类。

提前感谢您的任何建议。

【问题讨论】:

    标签: typescript ionic2 jasmine karma-jasmine


    【解决方案1】:

    是的,你可以在 Utils 类中添加一个 spy 来模拟 guard 方法。

    spyOn(Utils, 'guard').and.returnValue(true);
    

    【讨论】:

    • 谢谢。我的实际问题是有点循环引用,我在导入的静态类中引用了被测类,即我有 import { Dictionary } from './dictionary';在 Utils 类中
    猜你喜欢
    • 1970-01-01
    • 2017-02-16
    • 2019-03-26
    • 2021-03-12
    • 2020-08-24
    • 2022-11-11
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多