使用Tinytest异常进行测试
问题描述:
我正在使用包中的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"
);
});
是否有人知道如何测试异常以及提高吗?
答
好吧,我明白了。 首先,你必须使用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
);
这有什么错了'尝试catch'阻止? –
我不知道是否有'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