如何使用 Karma 测试 nodejs 后端代码(testacular)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16660670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test nodejs backend code with Karma (testacular)
提问by Sylvain
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 requireis undefined.
如何设置 Karma 来运行我的后端单元测试(用 Mocha 编写)?如果我将我的后端测试脚本添加到files = [],它会失败,说明require未定义。
采纳答案by Dan Kohn
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
你没有。Karma 仅用于测试基于浏览器的代码。如果您有一个项目,后端有 mocha 测试,前端有 karma/mocha 测试,请尝试在脚本下编辑 package.json 以将 test 设置为:mocha -R spec && karma run karma.con
Then, if npm testreturns true, you'll know it's safe to commit or deploy.
然后,如果npm test返回 true,您就会知道提交或部署是安全的。
回答by Sylvain
It seems like it cannot be done (thanks @dankohn). Here is my solution using Grunt:
似乎无法完成(感谢@dankohn)。这是我使用 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)
Karma:更新你的 karma.conf.js 文件
- 放
autoWatch = false; - 放
singleRun = true; - 设置
browsers = ['PhantomJS'];(具有内联结果)
- 放
咕噜声:
npm install grunt-contrib-watch grunt-simple-mocha grunt-karma- 配置两个 grunt 任务(参见下面的 grunt 文件)
Gruntfile.js:
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
gruntcommand.
Grunt(可选):配置 grunt-watch 在更改规范文件或要测试的文件后运行。
使用
grunt命令运行所有。

