Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test nodejs backend code with Karma (testacular)

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.

like image 824
Sylvain Avatar asked May 21 '13 01:05

Sylvain


People also ask

What is karma in Nodejs?

Karma is a test runner for JavaScript that runs on Node. js. It is very well suited to testing AngularJS or any other JavaScript projects. Using Karma to run tests using one of many popular JavaScript testing suites (Jasmine, Mocha, QUnit, etc.)

Can Nodejs be used for backend?

Yes, Node. js can be used in both the frontend and backend of applications. Let us now dive into a few of the applications that Node. js supports in the frontend and backend.


2 Answers

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.

like image 71
Dan Kohn Avatar answered Oct 02 '22 03:10

Dan Kohn


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)
  • 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.

like image 30
Sylvain Avatar answered Oct 02 '22 05:10

Sylvain