【问题标题】:Unit testing Typescript decorators单元测试 Typescript 装饰器
【发布时间】:2016-12-30 23:25:05
【问题描述】:

我有一个基于 typescript 的应用程序,带有装饰器,用于一些方便的属性分配,并且想知道如何为它们编写单元测试。

 export function APIUrl() {
        return function (target: any, key: string) {
             let _value = target[key];

          function getter() {
            return _value;
          }

          function setter(newValue) {
            _value = getApiURL();
          }

          if (delete target[key]) {
            Object.defineProperty(target, key, {
                get: getter,
                set: setter
            });
          }
        };
    }

在我的规范类中,

 it("should return url string", ()=> {
   @APIUrl();
   let baseURL:string;

   expect(baseURL typeOf string).toBe(true)
 })

【问题讨论】:

    标签: javascript unit-testing typescript


    【解决方案1】:

    由于装饰器只是函数,我建议像任何其他函数一样测试它们。只有当你真的需要时,才添加一个测试来展示如何将装饰器与类/成员/...

    这是一个这样的测试示例:

    import test from 'ava';
    import { APIUrl } from './path';
    
    const decorate = new APIUrl();
    
    test.before(t => {
      let obj = { someProp: 'foo' };
      decorate(obj, 'someProp');
      t.context.foo = obj;
    });
    
    test('should return original value', t => {
      t.is(t.context.foo.someProp, 'foo');
    });
    

    【讨论】:

    • 上述情况的任何例子,它接受参数并返回一个函数?
    • 我听不懂?你想看看上面的装饰器的测试吗?顺便说一句,您的测试规范不起作用,因为 TypeScript 不支持变量的装饰器。这符合官方草案规范。
    • 嗨@sebastian-sebald,是的,我想看看对上述装饰器的测试,我知道我的规范不起作用。
    • 添加了一个示例,但请注意,我不会为此编写整个测试套件;)这不是 SO 的用途!我只是表明装饰器只是函数。
    【解决方案2】:

    另一种方法是设置一些使用装饰器的属性和/或方法并直接测试它们的使用情况。

    注意:装饰器只能用于类方法和成员,因此您需要在测试中创建一个虚拟类。

    这是一个例子:

    //Test Setup
    class Test {
    
        @APIUrl()
        url: string;
    
        @AnotherDecorator()
        anotherFunction() {}
    
    }
    
    
    //Unit tests
    describe('Decorator Tests', () => {
        it('should work', () => {
           const t = new Test();
           expect(t.url).toEqual("something");
           expect(t.anotherFunction()).toReturn("something else");
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-02
      • 2012-04-26
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 2017-05-03
      • 2017-04-13
      • 2015-09-02
      • 2021-12-23
      相关资源
      最近更新 更多