我在Express中有以下内容
//index.js
var service = require('./subscription.service');
var auth = require('../auth/auth.service');
var router = express.Router();
router.post('/sync', auth.isAuthenticated, service.synchronise);
module.exports = router;
Run Code Online (Sandbox Code Playgroud)
我想覆盖或模拟isAuthenticated返回此
auth.isAuthenticated = function(req, res, next) {
return next();
}
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试:
it('it should return a 200 response', function(done) {
//proxyquire here?
request(app).post('/subscriptions/sync')
.set('Authorization','Bearer '+ authToken)
.send({receipt: newSubscriptionReceipt })
.expect(200,done);
});
Run Code Online (Sandbox Code Playgroud)
我尝试使用proxyquire模拟index.js - 我想我需要存根路由器?我也试过在测试中覆盖
app.use('/subscriptions', require('./api/subscription'));
Run Code Online (Sandbox Code Playgroud)
必须有一种简单的方法来模拟它,所以我不需要验证请求.有任何想法吗?
您好,我想对我的 Express JS 代码进行单元测试,我想模拟数据,因此在搜索多个网站和博客后,我找到了这个库,但我不清楚如何使用这个库进行模拟或数据。我的测试代码是
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();
});
});
});
Run Code Online (Sandbox Code Playgroud)
目前此代码正在从数据库获取数据,但我想使用模拟数据进行单元测试。我怎样才能做到这一点?
__编辑__
我想测试 Express …
我希望能够在每次测试的基础上存根我的中间件功能。正如此处阐明的,问题是我不能仅仅存根我的中间件函数,因为节点已经缓存了中间件函数,所以我不能存根它,因为我在一开始创建了我的应用程序。
const request = require("supertest");
const { expect } = require("chai");
const sinon = require('sinon');
const auth = require ("../utils/auth-middleware")
const adminStub = sinon.stub(auth, "isAdmin").callsFake((req, res, next) => next());
const app = require("../app.js"); // As soon as I create this, the middleware isAdmin function becomes cached and no longer mutable
Run Code Online (Sandbox Code Playgroud)
以上作为链接的SO答案中描述的解决方案,但我不喜欢那样为了恢复存根或修改假,我必须完全重新创建服务器。
我想知道是否有更好、更优雅的方法来解决 Node 首先缓存这些函数的事实require。我正在研究可能使用proxyquireordecache但两者似乎都提供了解决方法而不是可持续的解决方案(尽管我很可能在这里错了)。
node.js ×3
sinon ×3
express ×2
mocha.js ×2
javascript ×1
proxyquire ×1
sinon-chai ×1
unit-testing ×1