Skip to content

Instantly share code, notes, and snippets.

@sixFingers
Last active December 19, 2015 02:09
Show Gist options
  • Save sixFingers/5881446 to your computer and use it in GitHub Desktop.
Save sixFingers/5881446 to your computer and use it in GitHub Desktop.
Proof of concept for end-to-end testing in Meteor, with Phantom JS and... Meteor itself.

Prerequisites

Install phantomJS:

[sudo] npm install -g phantom

Create a /tests folder into your Meteor app:

cd [app folder] && mkdir tests && cd tests

Install node-phantom (https://github.com/alexscheelmeyer/node-phantom) locally into /tests folder:

[sudo] npm install node-phantom

Files and folder structure

Check this folder structure, creating files where necessary:

[app folder]/lib/tests.js                     <-- See below for content
[app folder]/tests/index.js                   <-- See below for content
[app folder]/tests/node_modules/node-phantom  <-- this should be already present after setup

Files content

/lib/tests.js:

Meteor.startup(function() {
  if(Meteor.isServer) {
    test = Npm.require('../../../../tests');
    phantom = Npm.require('../../../../tests/node_modules/node-phantom');
    test(phantom);
  }
});

Notes: being in lib, the file will be loaded before anything else. This should be in /lib when testing, and disappear when finished testing (or it would be packaged by Meteor). A good way would be to place it in /tests, then have a simple script make a symlink to this file in /lib, execute the tests, then remove the symlink.

/tests/index.js (code is obviously related to my application's code, i put it there to give a bit of skeleton).

module.exports = function(phantom) {
  if(Meteor.isServer) {
    console.log('I\'m the server!');

    Meteor.users.find().observe({
      added: function(user) {
        console.log(user);
      }
    });
  }

  phantom.create(function(err, ph) {
    ph.createPage(function(err, page) {
      return page.open("http://localhost:3000/user/register", function(err, status) {
        console.log('I\'m the client!', status);
        return page.evaluate(function() {
          Accounts.createUser({username: "Pinco Pallo", email: "weeemail@geeeemail.com", password: "abcdefghilmno"});
          // return document.title;
        }, function(err, result) {
          // console.log('Register result is: ' + result);
        });
      });
      ph.exit();
    });
  });
}

Launching the test session

At this point, launching meteor from the app folder will load the required modules and launch the tests. To make Meteor work on a different database (e.g. a "test" database), it has to be launched with a MONGO_URL env variable:

MONGO_URL=mongodb://localhost:27017/meteor_test meteor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment