摩卡柴testing受保护的路线

我有一个Express服务器,我使用passport-local进行身份validation。 我有以下受保护的路线:

app.post("/api/test", connect.ensureLoggedIn("/"), (req, res) => { let test = new Test(req.body); test .save() .then(data => { return res.json(data); }) .catch(e => { return res.status(HTTP_RESPONDE_BAD_REQUEST).send(e); }); }); 

我想知道如何testing上面提到的路线,确保用户login。

这是我目前的testing(它没有通过,因为我无法发送authentication:

 it("Testing protected route", done => { chai .request(server) .post("/api/test") .send(test) .end((err, res) => { expect(res.status).to.equal(200); done(); }); }); 

我已经尝试了以下,但是当我运行testing他们redirect到login页面。

 it("Testing protected route", done => { chai .request(server) .post("/api/test") .set('Authorization', 'Bearer ' + token) // user token id .send(test) .end((err, res) => { expect(res.status).to.equal(200); done(); }); }); it("Testing protected route", done => { chai .request(server) .post("/api/test") .set('token', token) // user token id .send(test) .end((err, res) => { expect(res.status).to.equal(200); done(); }); }); 

有没有更简单的方法来testing这个?

我使用supertestmocha作为我的unit testing以及标记的自定义标题,但是我的testing使用了类似的模式。 在运行任何testing之前,将数据加载到数据库中,然后用户login,然后将该令牌用于需要validation的每个testing。

TestUtils类

  this.authenticateUser = (user, app) => new Promise((resolve, reject) => { request(app) .post('/authenticate') .send({ email: user.email, password: user.test_password, }) .end((err, res) => { if (err) { return reject(err); } return resolve(res.body.token); }); }); 

testing类

 describe('Authed Routes', () => { let app = null; let authUser = null; before((done) => { // mocking should happen before the app is created. app = require('../server'); // Populate redis data TestUtils.populateRedis(() => { // Populate db data TestUtils.syncAndPopulateDatabase('public-tests', () => { // Get the test user authUser = TestUtils.getUser(); // Authenticate the user to get a token TestUtils.authenticateUser(authUser, app) .then((accessToken) => { // Keep the token on the user so we can use it in the tests authUser.access_token = accessToken; return done(); }) .catch((err) => done(err)); }); }); }); describe('/secure/route', () => { it('should allow /secure/route with correct token provided', (done) => { request(app) .get('/secure/route') // add the access token from the user as a header value .set('x-access-token', authUser.access_token) .expect(200) .end((err, res) => { done(); }); }); }); });