如何用 Karma (testacular)测试 nodejs 后端代码

如何设置 Karma 来运行后端单元测试(使用 Mocha 编写) ?如果我将我的后端测试脚本添加到 files = [],它将失败,因为它指出 require是未定义的。

41922 次浏览

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.

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.