我想测试一个内部调用供应商中间件函数的中间件函数。中间件是:
const expressJwt = require('express-jwt');
const validateJwt = expressJwt({ secret: 'whatever' });
exports.isAuthenticated = (req, res, next) => {
if (req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = `Bearer ${req.query.access_token}`;
}
validateJwt(req, res, next);
};
我尝试创建sinon.spy()
对象并将其作为next
参数传递,但显然不会被调用。
我尝试过的另一种方法是检查是否存在req.user
,因为express-jwt
中间件的目的是验证并user
req
<dependency>
<groupId>org.apache.maven.surefire</groupId>
<artifactId>common-java5</artifactId>
<version>2.16</version>
</dependency>
宾语。也没有运气。
我已经看到了chai-connect
的存在,但不确定如何使用它。
有什么想法吗?非常感谢!
答案 0 :(得分:0)
我终于设法使用proxyquire
和chai-connect
:
在你的mocha配置中:
chai.use(require('chai-connect-middleware'));
global.connect = chai.connect;
在你的测试中:
describe('isAuthenticated', () => {
// Wrap call to chai.connect into a function to use params and return a Promise
const mockedMiddleware = (changeSecret) => {
let oldToken;
if (changeSecret) {
oldToken = acessToken;
acessToken = 'blabalblalba';
}
return new Promise((resolve, reject) => {
connect.use(middleware.isAuthenticated)
.req(req => {
req.query = { access_token: acessToken };
})
.next((res) => {
acessToken = oldToken;
if (res && res.status === 401) {
reject(res.message);
} else {
resolve();
}
})
.dispatch();
});
};
it('should validate correctly', () =>
mockedMiddleware().should.be.fulfilled
);
it('should not validate', () =>
mockedMiddleware(true).should.be.rejected
);
});