节点js的unit testing

我是nodejs的新手,需要为节点项目编写unit testing。 我尝试学习摩卡,有两个问题:

  1. 当我为函数A编写unit testing时,在A中也使用函数B,那么我怎样才能模拟B的输出呢?

  2. 我如何在app.js中unit testing这些端点 像app.get,app.put。 有人可以给我一些build议或简单的例子吗?

有人可以给我一些关于编写nodejsunit testing的build议,非常感谢。

非常感谢大家。

回答Q1,

如果在方法中使用b方法的输出,则可以先进行b方法的testing。

否则,你可以在你的testing方法before准备b结果,并在a方法中使用它。

这取决于你的testing方法。

回答Q2 –

您可以使用superagent发送获取或发送请求…

一些代码示例…

require('should'); var assert = require("assert"); var request = require('superagent'); var expect = require('expect.js'); 然后,

describe('yourapp', function(){ before(function(){ // function start start your server code // function end }) describe('server', function(){ describe('some-description', function(){ it('should return json in response', function(done){ request.post('http path') .send(JSON.parse("your json")) .end(function(res){ expect(res).to.exist; expect(res.status).to.equal(200); expect(res.text).to.contain('ok'); done(); }); }) }); }) after(function(){ //stop your server }) }); 这里做的是asynchronous方法testing的unit testing组件中的一个重要方面。

一些参考 –

的SuperAgent

这篇博文

希望对你有帮助,

谢谢

我最近参与了一个节点项目,我必须运行unit testing。 最后我用NW.JS写了一个小型的业余脚本运行者,这让我可以访问所有节点模块,并在服务器上运行我的testing。 我把这个项目上传到了Narma的 github。 目前它只在Mac上进行testing

回答Q1,

如果function在不同的模块中,可以使用模拟工具: fremock

使用freemock你可以这样做:

你的代码

 //function a exports in the module named mA function a(){ return "1"; } //function a exports in the module named mB function b(){ a(); } 

testing代码

 var freemock = require('freemock'); freemock.start() var mock_b = freemock.getMock('mB'); mock_b.setMethod({ "a":{ willReturn:"1" } }) freemock.end(); 

一些忠告:

摩卡是node.js的良好testing框架。

例如,

  1. 断言工具:should.js
  2. 代码覆盖工具:伊斯坦布尔

摩卡结合了所有这些工具;

这是一个使用摩卡的演示:

你的代码(文件名:mA.js)

 //in the module named mA function a(){ return true; } 

testing代码(文件名:testmA.js)

 var should = require('should'); beforeEach(function(){ //do something before testing }); afterEach(function(){ //do something after testing }); describe("test",function(){ describe("test1",function(){ it("if true",function(){ var mA = require('./mA'); var result = mA.a(); should.ok(result); }); it("if false",function(){ //other test }); }); describe("test2",function(){ it("test2-1",function(){ //other test }) }) }) 

我们应该需要run.js来开始testing:

 //run.js var Mocha = require('mocha'); var mocha = new Mocha; mocha.addFile(__dirname+'/test/testmA.js') mocha.run(); 

项目目录树是:

 |- run.js | |- mA.js | |- test - testMA.js 

最后

运行这个命令:

 istanbul cover run.js 

希望你喜欢!