簡體   English   中英

如何測試需要用戶在 Express 中進行身份驗證的請求

[英]How to test requests that require the user to be authenticated in Express

如何測試需要用戶進行身份驗證的請求? 我在我的快遞應用程序中使用本地 passport.js。 我正在使用 Jest 和 Supertest 進行測試。 我查閱了無數帖子,我嘗試了 supertest-session ,但這似乎也不起作用。 所有這些帖子都是近 10 年前的,所以我不確定它們是否仍然有效。

這是我嘗試過的最后一件事:

const request = require('supertest');
const app = require('../app');
const { pool } = require('../dbConfig');
let testAccount = { email:  'loginTestUser@gmail.com', password: '123456' }

const loginUrl = '/users/login';
const createRoomUrl = '/rooms/create'
const successfulRoomCreateUrl = '/users/dashboard';
const successfulLoginUrl = '/users/dashboard';
const failedRoomCreateUrl = '/';


afterAll(async () => {
    pool.end();
});


describe('Room CRUD: Create | POST /rooms/create', () => {
    describe('Given the user is Authenticated', () => {
        let token;
        beforeEach( async () => {
        const response = await
            request(app).post(loginUrl).type('form').send(testAccount);
        token = { access_token: response.body.token }
    });

    test(`should get statusCode 200 if user is logged in`, async () => {
        const createRoomResponse = await request(app).get(createRoomUrl).query(token);
        // 302 since the user doesn't stay logged in
        expect(createRoomResponse.statusCode).toEqual(200);
    });
});
});

這是我嘗試使用 supertest-session 的方法,但它也不起作用:

const session = require('supertest-session');
const myApp = require('../app');
let testAccount = { email:  'loginTestUser@gmail.com', password: '123456' }

var testSession = null;
 
beforeEach(function () {
  testSession = session(myApp);
});

it('should fail accessing a restricted page', function (done) {
  testSession.get('/rooms/create')
    .expect(302)
    .end(done)
});
 
it('should sign in', function (done) {
  testSession.post('/users/login')
    .send(testAccount)
    .expect(302) // get redirected to dashboard
    .end(done);
});

describe('after authenticating session', function () {
 
  var authenticatedSession;
 
  beforeEach(function (done) {
    testSession.post('/users/login')
      .send(testAccount)
      .expect(302) // get redirected to /users/dashboard
      .end(function (err) {
        if (err) return done(err);
        authenticatedSession = testSession;
        return done();
      });
  });
 
  it('should get a restricted page', function (done) {
    authenticatedSession.get('/rooms/create')
      .expect(200) // <------ still get a 302 (redirect if user !logged
      .end(done)
  });
});

原來我需要做的就是像這樣附加.type('form')

beforeEach(function (done) {
  testSession.post('/users/login').type('form')
    .send(testAccount)
    .expect(302) // get redirected to /users/dashboard
    .end(function (err) {
      if (err) return done(err);
      authenticatedSession = testSession;
      return done();
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM