2015-10-05 163 views
0

我創建了一個裝飾,它包含一個規則,當它使用的不是同一個班一次扔,它的一個非常基本的版本將是類似以下內容:斷言裝飾拋出

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 { 

} 

一切按預期工作由我想寫一個單元測試來驗證此功能。我正在使用摩卡,柴和sinon。

我怎麼能斷言someDecorator拋出?

回答

0

我該如何斷言someDecorator會拋出?

你基本上想要調用它兩次(someDecorator(someDecorator(function(){}))和assert a throw

0

做的另一種可能的方式:

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); 
    }); 
}); 
相關問題