【发布时间】:2022-01-13 17:03:08
【问题描述】:
我有一个任务来实现类装饰器,以添加“identify”类方法,该方法返回一个类名以及装饰器中传递的信息。
例如:
@identifier('example')
class Test {}
const test = new Test();
console.log(test['identify']()); // Test-example
当我控制台日志显示类名和括号中的字符串时,它给了我预期的结果。主要问题是当我运行测试单元时:
describe('identifier', () => {
it('should return Test-example from identify', () => {
@identifier('example')
class Test {}
const test = new Test();
assert.strictEqual(test['identify'](), 'Test-example');
});
it('should return ClassA-prototype from identify', () => {
@identifier('prototype')
class ClassA {}
const test = new ClassA();
assert.strictEqual(test['identify'](), 'ClassA-prototype');
})
});
装饰器实现:
方法一:
function identifier(...args: any): ClassDecorator {
return function <TFunction extends Function>(
target: TFunction
): TFunction | any {
return target.name + "-" + args;
};
}
方法二:
function identifier(passedInformation: string): any {
return function (target) {
return target.name + "-" + passedInformation;
};
}
我认为这两个函数都很好,但是在 junit.xml 中都给了我同样的错误:
<testcase name="identifier should return Test-example from identify" time="0.0000" classname="should return Test-example from identify">
<failure message="" type="TypeError"><![CDATA[TypeError:
at DecorateConstructor (node_modules\reflect-metadata\Reflect.js:544:31)
at Object.decorate (node_modules\reflect-metadata\Reflect.js:130:24)
at __decorate (test\index.ts:4:92)
at C:\Users\artio\Desktop\6 Decorators\decorators\test\index.ts:81:20
at Context.<anonymous> (test\index.ts:85:10)
at processImmediate (internal/timers.js:439:21)]]></failure>
</testcase>
<testcase name="identifier should return ClassA-prototype from identify" time="0.0000" classname="should return ClassA-prototype from identify">
<failure message="" type="TypeError"><![CDATA[TypeError:
at DecorateConstructor (node_modules\reflect-metadata\Reflect.js:544:31)
at Object.decorate (node_modules\reflect-metadata\Reflect.js:130:24)
at __decorate (test\index.ts:4:92)
at C:\Users\artio\Desktop\6 Decorators\decorators\test\index.ts:93:22
at Context.<anonymous> (test\index.ts:97:10)
at processImmediate (internal/timers.js:439:21)]]></failure>
</testcase>
有谁知道问题出在哪里,我该如何解决?由于这些错误,我无法通过任务...要提一下,我无法修改单元测试,只能修改功能。
【问题讨论】:
标签: typescript decorator