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.
How to test nodejs backend code with Karma (testacular)
Asked Answered
This CAN be done, take look at my project: github.com/noamtcohen/Narma –
Chianti
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. –
Coarsegrained
Basically all test runners for JS rely on a browser then? That's useless. –
Unidirectional
Mocha and Jasmine don't rely on a browser, and when you want to run ona headless browser, consider using phantomjs. –
Vanmeter
Notice 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. –
Whirl
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.
So 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. –
Unidirectional
Hi, 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. –
Coarsegrained
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. –
Pacificism
Interesting approach. But how do you ensure that Sails globals are properly recognised within your tests? –
Chigger
© 2022 - 2024 — McMap. All rights reserved.