2015-10-13 42 views
1

我正在使用包中的Tinytest進行單元測試,我想測試一種方法引發異常,我可以使用test.throws()對其進行測試。使用Tinytest異常進行測試

我創建了一個流星項目:

meteor create myapp 
cd myapp 
meteor add tinytest 

要創建一個包,我做

meteor create --package test-exception 

這是我簡單的測試
文件test-exception.js

Joe = { 
    init: function() { 
     throw "an exception"; 
    } 
} 

文件package.js

Package.describe({ 
    name: 'tinytest-throws', 
    version: '0.0.1' 
}); 

Package.onUse(function(api) { 
    api.versionsFrom('1.2.0.2'); 
    api.use('ecmascript'); 
    api.addFiles('tinytest-throws.js'); 

    api.export('Joe', 'server'); // create a global variable for the server side 
}); 

Package.onTest(function(api) { 
    api.use('ecmascript'); 
    api.use('tinytest'); 
    api.use('tinytest-throws'); 
    api.addFiles('tinytest-throws-tests.js', 'server'); // launch this test only as server 
}); 

文件test-exception-tests.js

Tinytest.add('Call a method that raise an exception', function (test) { 
    test.throws(
     Joe.init, // That could be a way, but this fails 
     "This is an exception" 
    ); 

    test.throws(
     Joe.init(), 
     "This is an exception" 
    ); 
}); 

是否有人知道如何測試異常以及提高嗎?

+0

這有什麼錯了'嘗試catch'阻止? –

+0

我不知道是否有'test.ok()'和'test.fail()'withTinytest(食譜中沒有跟蹤:https://github.com/awatson1978/meteor-cookbook/blob/master/ cookbook/writing.unit.tests.md#tinytest-api),而我不想在'test.throws()'存在時使用'test.isTrue(true)'。 – Ser

回答

1

好吧,我明白了。 首先,你必須使用Meteor.Error。所以我Joe對象變爲:

Joe = { 
    init: function() { 
     throw new Meteor.Error("This is an exception"); 
    } 
} 

現在,我可以使用Test.throws捕獲錯誤:

test.throws(
    function() { 
     Joe.init() 
    }, 
    "n except" // a substring of the exception message 
);