单元测试Typescript装饰器



我有一个基于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
            });
          }
        };
    }

在spec类中,我有

 it("should return url string", ()=> {
   @APIUrl();
   let baseURL:string;
   expect(baseURL typeOf string).toBe(true)
 })

由于decorator只是函数,我建议像测试其他函数一样测试它们。只有当你真的需要的时候,添加一个测试来展示如何在类/成员/…中使用装饰器。

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

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');
});

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

注意:装饰器只能在类方法和成员上使用,所以你需要在测试中创建一个虚拟类。

下面是一个例子:

//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");
    });
}

最新更新