Meteor unit tests with Jest, 2019 edition

Xavier Priour
2 min readFeb 13, 2019

--

I have a confession to make: my Meteor app, in production for more than 2 years, has no tests. So today I embarked on a journey to change that, starting with the basics: unit tests (no integration, no end-to-end yet). Read on if you’re in the same boat!

https://blog.meteor.com/real-world-unit-tests-with-meteor-and-jest-3d557e84e84a

In the grand JavaScript tradition, we first need to choose our library before we can do anything. I went with Jest, because it seems like the growing consensus according to the State of JavaScript 2018 (plus Facebook, podcasts, zeitgeist, gut feeling, yada yada).

Jest documentation is great, but having it work with Meteor was not as straightforward as I had hoped (blame imports and oldish babel dependencies). The official pages don’t talk about it (neither Meteor nor Jest), and though multiple articles exist (here, here, and here), they weren’t fully up-to-date, and usually too complex for my current use case (just unit tests, remember).

So here’s the simplest way to add Jest unit tests to Meteor as of February 13th, 2019:

  • ensure the element you want to test is in a separate file, with no dependencies on Meteor elements (typically, isolate it in a function).
  • Add a simple test file just by its side, called sameFilename.test.js (see Jest doc on how to write a test)
  • add the right dependencies: meteor npm i -D jest @babel/core @babel/preset-env @babel/preset-react (react is only needed if you have React code to test)
  • add a .babelrc file to your project root, with content:
{
"env": {
"test": {
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}
}
}
  • update your package.json to include your test command:
"scripts": {
"start": "meteor run",
"test": "jest"
},
  • run your tests: meteor npm test
  • and you’re done!

Note that this setup has a strong limitation: it will only run isolated, vanilla JavaScript code, with no Meteor-specific elements. I find this a very good thing for unit tests, personally. Next step: run full end-to-end tests. Until then, happy meteors to you all!

--

--