meteorexceptiontinytestmeteor-packages

Testing with Tinytest exceptions


I am working on unit test using Tinytest in a package and I wanted to test that a method raise an exception and I can test it using test.throws().

I create a meteor project :

meteor create myapp
cd myapp
meteor add tinytest

To create a package, I do

meteor create --package test-exception

And this is my simple test
File test-exception.js

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

File 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
});

File 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"
    );
});

Does somebody know how to test that exceptions are well raised ?


Solution

  • Ok I get it. First, you have to use Meteor.Error. So my Joe object becomes :

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

    Now, I can catch the error using Test.throws :

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