我是Javascript测试的新手,并尝试使用mocha和chai测试我的NodeJS后端。 我的所有路线如何填充中间件,如果他们没有登录,则不允许人们继续前进。
像这样的东西
app.post('/user/analytics/driverdata', checkauth, function(req, res) {
analytics.driverData(req, res);
});
其中checkauth
是
var checkauth = function(req, res, next) {
console.log("In checkauth");
if (req.isAuthenticated()) {
next();
} else {
console.log("Doesn't authenticate");
res.status(401);
res.set('Content-Type', 'application/json');
res.end(JSON.stringify({
'success': false
}));
}
};
当PassportJS反序列化请求时,isAuthenticated参数附加到PassportJS的请求。 我想做的是为
编写一个测试app.post('/user/analytics/driverdata', checkauth, function(req, res) {
analytics.driverData(req, res);
});
此API。我失败了,因为我没有登录,因此无法到达那里。
所以我写了一个beforeEach来登录用户beforeEach it
。它是这样的。
var expect = require('chai').expect;
var request = require('superagent');
beforeEach(function(done){
//login into the system
request
.post("http:localhost:5223/user/authenticate/login")
.send({username : "saras.arya@gmail.com", password : "saras"})
.end(function assert(err, res){
if(err){
console.log(err);
done();
}
else{
done();
}
});
});
我不知道自己做错了什么,互联网让我失望了。任何帮助指出我出错的地方将不胜感激。
答案 0 :(得分:0)
在看到很多东西和烦躁不安之后,我想我终于破解了它。如果将the answer here介绍给代理人的概念,那就太苛刻了。哪个帮我解决了这个问题。
在您的describe块中,或者可能在块之前,您可以拥有以下it
。
var superagent = require('superagent');
var agent = superagent.agent();
it('should create a user session successfully', function(done) {
agent
.post('http://localhost:5223/user/authenticate/login')
.send({
username: 'whatever@example.com',
password: 'ssh-its-a-secret'
})
.end(function(err, res) {
console.log(res.statusCode);
if (expect(res.statusCode).to.equal(200))
return done();
else {
return done(new Error("The login is not happening"));
}
});
});
代理变量为您保存cookie,然后PassportJS使用它来验证您的身份。
这是你如何做到的。因此,代理变量位于describe
内。在另一个describe
内的it
内。
it("should test analytics controller", function(done) {
agent.post('http://localhost:5040/user/analytics/driverData')
.send({
startDate: "",
endDate: "",
driverId: ""
})
.end(function(err, res) {
if(!err)
done();
});
});
此功能像魅力一样传递。这是一个缺失的完整文档。