Test-only utilities

Hi,

I would like to specify some utility code for my tests as functions that can only run in test mode (when meteor.isTest is true).
However I would like to avoid to have to put an if (Meteor.isTest) on every function.
I would rather, similarly to what is possible with isClient and isServer, have a folder path that would prevent the code to be loaded/executed if meteor is not in test mode.
Client and server have the “client” and 'server" folder convetions.

Basically I would like the same for testing code so that it only can get executed during test mode.

Meteor does provide a “tests” special folder path, however that one basically prevents loading completely as it is meant to be used for external (outside of meteor) tests.

So is there a way to achieve what I want without having to manually specifiy Meteor.isTest everywhere?

Thanks!

If your code is in a package, you can add an onTest to the package file to indicate files you would like to load during a test:

Package.describe({
  name: 'your:package',
  version: '0.0.1',
  summary: '...',
  git: '...',
  documentation: 'README.md',
});

var dependencies = [
  'ecmascript',
  'underscore',
];

Package.onUse(function(api) {
  api.versionsFrom('METEOR@1.4');
  api.use(dependencies, ['client', 'server']);
  api.mainModule('client/main.js', 'client');
  api.mainModule('server/main.js', 'server');
});

Package.onTest(function(api) {
  api.versionsFrom('METEOR@1.4');

  api.use(dependencies);
  api.use([
    'tinytest',
    'practicalmeteor:sinon', // or your test library of choice
    'your:package', // don't forget to depend on your package under test here
  ]);

  api.mainModule('client/test.js', 'client');
  api.mainModule('server/test.js', 'server');
});

Here, during a test, the entry points will be client/test.js and server/test.js on the client and server, respectively. You can import test-only files in each of them.

If you’re using Meteor 1.7, you can also take advantage of the new testModule option in package.json mentioned in the release notes here: https://docs.meteor.com/changelog.html#v1720180528