This solution may not be ideal as it can override the onAfterAction hook if already defined, and it introduces onRendered functions to templates which can complicate testing.
testing-router-helper.js
import { Template } from 'meteor/templating';
import { Tracker } from 'meteor/tracker';
import { Router } from 'meteor/iron:router';
export const testRouteRendering = function(templates, callback) {
let routeRendered = new ReactiveVar(false);
Router.onAfterAction(function() {
routeRendered.set(true);
});
let templatesRendered = [];
if (Array.isArray(templates)) {
templates.forEach(function(templateName) {
let rendered = new ReactiveVar(false);
Template[templateName].onRendered(function() {
rendered.set(true);
});
templatesRendered.push(rendered);
});
}
Tracker.autorun(function() {
const areTemplatesRendered = templatesRendered.every(function(rendered) {
return rendered.get();
});
if (routeRendered.get() && areTemplatesRendered) {
Router.onAfterAction(function() {});
if (callback) {
callback();
}
}
});
};
test-router.html
<template name="placeholderLayout">{{> yield}}</template>
<template name="placeholderTemplate"></template>
test-router.js
import { chai } from 'meteor/practicalmeteor:chai';
import { testRouteRendering } from './testing-router-helper.js';
import './test-router.html';
import './router.js';
const RoutesToTest = [
{ name: 'about', path: '/about', template: 'aboutPage', layout: 'defaultLayout' }
// additional routes
];
describe('router testing', function() {
before(function() {
Router.route('/exampleRoute', { name: 'exampleRoute', template: 'exampleTemplate', layoutTemplate: 'exampleLayout' });
});
beforeEach(function(done) {
Router.go('exampleRoute');
testRouteRendering(['exampleTemplate'], done);
});
after(function() {
Router.go('/');
});
RoutesToTest.forEach(function(testRoute) {
let message = 'testing route ' + testRoute.name + ' with path ' + testRoute.path;
message += ' should render template ' + testRoute.template + ' with layout ' + testRoute.layout;
it(message, function(done) {
Router.go(testRoute.name);
testRouteRendering([testRoute.template, testRoute.layout], function() {
// verifies that the route and templates have been rendered correctly, otherwise the test will timeout
chai.assert.equal(Router.routes[testRoute.name].path(), testRoute.path);
done();
});
});
});
});