【问题标题】:Assert decorator throws断言装饰器抛出
【发布时间】:2015-10-05 22:15:13
【问题描述】:

我创建了一个装饰器,它包含一个规则,当它与一个类一起使用不止一次时,它的一个非常基本的版本将类似于以下内容:

function someDecorator(target: any) {
    var msg = "Decorator can only be applyed once";
    if(target.annotated != undefined) throw new Error(msg);
    target.annotated = true;
}

因此,如果开发人员多次尝试使用该开发人员,它会抛出:

@someDecorator
@someDecorator // throws
class Test {

}

一切都按预期工作,我想编写一个单元测试来验证此功能。我正在使用 mocha、chai 和 sinon。

我如何断言 someDecorator 抛出?

【问题讨论】:

    标签: typescript mocha.js decorator sinon chai


    【解决方案1】:

    我如何断言 someDecorator 抛出?

    你基本上想调用它两次(someDecorator(someDecorator(function(){}))和assert a throw

    【讨论】:

      【解决方案2】:

      另一种可能的方法:

      declare function __decorate(decorators, target, key?, desc?);
      declare function __param(paramIndex, decorator);
      
      describe("@named decorator \n", () => {
        it("It should throw when applayed mutiple times \n", () => {
      
          var useDecoratorMoreThanOnce = function() {
            __decorate([
                __param(0, named("a")),
                __param(0, named("b"))
            ], NamedTooManyTimesWarrior);
          };
      
          var msg = "Metadadata key named was used more than once in a parameter.";
          expect(useDecoratorMoreThanOnce).to.throw(msg);
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2011-12-23
        • 2017-05-02
        • 1970-01-01
        • 2011-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多