简体   繁体   English

单元测试 Typescript 装饰器

[英]Unit testing Typescript decorators

I have an application built on typescript with decorators for some convenience property assignments and wondering how I can go about writing unit tests for them.我有一个基于带有装饰器的打字稿的应用程序,用于一些便利的属性分配,并想知道如何为它们编写单元测试。

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

In a spec class I have,在我有的规范类中,

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

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

Since decorators are just functions I would suggest to just test them like any other function.由于装饰器只是函数,我建议像任何其他函数一样测试它们。 And only if you really need to, add one tests that shows how to use the decorator with a class/member/...并且仅当您确实需要时,添加一个测试来展示如何将装饰器与类/成员/...

Here is an example such a test could look like:这是一个这样的测试示例:

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

Another approach could be to setup some properties and/or methods that use your decorators and test their usage directly.另一种方法可能是设置一些使用装饰器的属性和/或方法并直接测试它们的使用。

Note: decorators can only be used on class methods and members so you'd need to create a dummy class in your test.注意:装饰器只能用于类方法和成员,因此您需要在测试中创建一个虚拟类。

Here's an example:下面是一个例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM