简体   繁体   中英

Mocha Chai Testing protected route

I have an Express server and I'm using passport-local for authentication. I have the following protected route:

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);
  });
});

I was wondering how can I test the route mentioned above ensuring the user is logged on.

This is my current test (it does not pass, because I wasnt able to send authentication:

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

I have tried the following, but when I run the test they redirect me to the login page.

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();
  });
});

Is there an easier way to test this?

I am using supertest and mocha for my unit tests as well as a custom header for the token, but am using a similar pattern for my tests. Before any tests are run the data is loaded into the database and the user is logged in, then that token is used for each of the tests that need authentication.

TestUtils class

  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);
      });
    });

Test Class

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();
      });
    });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM