如何用Express jsunit testing来使用sinon js

您好我想对我的快速js代码进行unit testing,我想嘲笑数据,所以search多个网站和博客后,我发现这个库,但我不清楚如何使用这个库嘲笑或数据。 我的testing代码是

var request = require('supertest'); var server = require('./app'); var chai = require('chai'); var chaiHttp = require('chai-http'); var server = require('./app'); var should = chai.should(); chai.use(chaiHttp); describe('loading express', function () { it('responds to /', function testSlash(done) { request(server) .get('/') .expect(200, done); }); it('404 everything else', function testPath(done) { request(server) .get('/foo/bar') .expect(404, done); }); it('responds to /customers/getCustomerData', function testPath(done) { request(server) .get('/customers/getCustomerData?id=0987654321') .end(function(err, res){ res.should.have.status(200); res.body.should.be.a('object'); res.body.status.should.equal("success"); res.body.data.customerId.should.equal("0987654321"); done(); }); }); }); 

目前这个代码是从数据库中提取数据,但我想unit testing使用模拟数据。 我怎么能做到这一点?

__编辑__

我想testing一下Express js路由文件里面写的代码。 这条路线我打电话给这样的app.js文件

 var customers = require('./routes/customers'); app.use('/customers', customers); 

现在客户路由文件包含的代码是

 function getCustomerData(req, res, next) { var response = {}; var cb = function (response) { res.send(response); } var modelObj = req.models.customer_master; var data = req.query; controllers.customers.get(modelObj, data, cb); }; router.get('/getCustomerData', function (req, res, next) { getCustomerData(req, res, next); }); 

我想使用模拟数据来testing“get”方法的响应

我想猜测你的控制器中间件。 由于您没有提供任何服务器端代码,我只是想一些事情:

 app.get('/', rootController.get); 

现在你想存根这个控制器:

 it('responds to /', function testSlash(done) { const rootController = require('./path/to/your/controller'); const rootControllerStub = sinon.stub(rootController, "get", function(req, res, next){ res.status(200).json({stubbed: 'data'}); }); request(server) .get('/') .expect(200) .expect({stubbed: 'data'}) .end(done); }); 

如果你想模拟,你可以在这里使用sinon express模拟,或者如果你想testing实际的响应数据,JSON,使用这个例子

示例中的快速路由接受一个参数并返回一个JSON

 it('should respond with JSON data', function (done) { request(server) .get('/about/jv') .expect(200) .end(function (err, response) { assert.equal(response.header['content-type'], 'application/json; charset=utf-8'); assert.deepEqual(response.body, { "data":{ "username":"hellojv"} }); done(); }); 

但如上所述,如果你想使用sinon,那么使用模拟库。 这个例子使用了Mocha和超类。