How do I setup Karma to run my backend unit tests (written with Mocha)? If I add my backend test script to the files = []
, it fails stating that require
is undefined.
Asked
Active
Viewed 4.2k times
87

Sylvain
- 19,099
- 23
- 96
- 145
-
This **CAN** be done, take look at my project: https://github.com/noamtcohen/Narma – noamtcohen Mar 30 '15 at 23:35
2 Answers
84
You don't. Karma is only for testing browser-based code. If you have a project with mocha tests on the backend and karma/mocha on the front end, try editing your package.json under scripts to set test to: mocha -R spec && karma run karma.con
Then, if npm test
returns true, you'll know it's safe to commit or deploy.
-
Thanks! I found a solution using Grunt which I was already planning on setting up in my project. See my own answer. – Sylvain May 23 '13 at 03:44
-
-
4Mocha and Jasmine don't rely on a browser, and when you want to run ona headless browser, consider using phantomjs. – Dan Kohn Jan 19 '14 at 20:14
-
3Notice that relying on a browser for testing is NOT something bad. There are different kinds of tests and end to end testing is valid, dependending on your needs. Even testing visual regression (see facebook's huxley) is important in some cases. – Ciro Costa Aug 22 '14 at 03:40
15
It seems like it cannot be done (thanks @dankohn). Here is my solution using Grunt:
Karma: update your karma.conf.js file
- set
autoWatch = false;
- set
singleRun = true;
- set
browsers = ['PhantomJS'];
(to have inline results)
- set
Grunt:
npm install grunt-contrib-watch grunt-simple-mocha grunt-karma
- configure the two grunt tasks (see grunt file below)
Gruntfile.js:
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-karma');
grunt.initConfig({
simplemocha: {
backend: {
src: 'test/server-tests.js'
}
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
}
});
// Default task.
grunt.registerTask('default', ['simplemocha', 'karma']);
};
Grunt (optional): configure grunt-watch to run after changing spec files or files to be tested.
run all using
grunt
command.
-
3So you still require a browser, it's just that the browser is a headless one. How useless, definitely not using karma for server side testing. – Jan 19 '14 at 19:42
-
6Hi, this is not using karma for backend, this is using mocha, so no browser. This is just a convenient way of running all your tests as soon as you save a file. – Sylvain Jan 21 '14 at 14:27
-
While I didn't really need Karma for what I was doing, this did lead me down an easy path to get grunt setup to run my mocha tests automatically, so thanks for that. – Michael Oryl Mar 21 '14 at 13:39
-
Interesting approach. But how do you ensure that Sails globals are properly recognised within your tests? – dmvianna Oct 28 '15 at 01:45