Jest使用快速会话的请求会话

umuewwlo  于 2023-04-27  发布在  Jest
关注(0)|答案(1)|浏览(152)

我正在测试一个使用req.session的路由,有人能帮我模拟一下会话吗?
登录功能是这一个,我试图使用supertest-session模拟一个会话,但它只与cookie会话时,即时通讯使用快速会话

app.post('/login', (req, res) => {
    console.log(req.body)
    let id = req.body.loginID
    let mdp = req.body.loginPwd

    if (id != '' && id != undefined) {
        if (mdp != '' && mdp != undefined) {
            let Login = require('../models/M_Login')
            Login.testLogin(id,mdp, (result, id) => {
                console.log(result)
                switch (result.resultCode) {
                    case 0:
                        req.session.infoUser = result
                        req.session.infoUser.loginNo = id
                        req.session.success = 'Connexion réussie'
                        res.redirect('/accueil')
                        break
                    case 2001:
                        req.session.error = 'Identifiant inconnu'
                        res.redirect('/')
                        break
                    case 2002:
                        req.session.error = 'Mot de passe incorrect'
                        res.redirect('/')
                        break
                    case 1003:
                        req.session.error = 'Compte bloqué veuillez contacter l\'administrateur'
                        res.redirect('/')
                        break
                }
            })
        } else {
            req.session.error = 'Vous devez renseigner votre mot de passe'
            res.redirect('/')
        }
    } else {
        req.session.error = 'Vous devez renseigner votre identifiant'
        res.redirect('/')
    }
})

这是路线和

app.get('/getKeyListFromBox', (req, res) => {

    if (req.session.infoUser != undefined) {
        let key = require('../models/M_Key')
        key.indexByBox(req.query.boxID)
            .then(data => {
                res.json(data)
            })
            .catch(e => {
                res.json('Erreur: ' + e)
            })
    } else {
     req.session.error = 'Vous devez vous connecter'
       res.redirect('/')
    }
})

这是测试

it('getKeyListFromBox', async () => { 
        
        let resultat = await request(app).get('/getKeyListFromBox').query({boxID:6269})
        
        expect(resultat.statusCode).toBe(200)
    })

这是我使用的express会话的配置

app.use(session({
    secret: 'Hex@c0',
    resave: false,
    saveUninitialized: true,
    cookie: {secure: false}
}))
const log = false;

有人能帮帮我吗?

f4t66c6m

f4t66c6m1#

这个扭曲的黑客应该工作(应该至少与express-session@1.17.3工作。我从它的代码派生这个解决方案。

// the testee app

const sessionStore = YOUR_STORE; // a MemoryStore should be fine. Test code requires access to this store too (in 'createSessionCookie').

const sessionMiddleware = require('express-session')({
  secret: SECRET,
  store: sessionStore,
});

const app = require('express')()
app.use(sessionMiddleware)

module.exports = app;
// the test code
import supertest from 'supertest'
import {app, sessionStore, SECRET} from './app'
import cookie from 'cookie'
import {promisify} from 'node:util'
import signature from 'cookie-signature'

async function createSessionCookie(sessionValue: any): Promise<string> {
  const fakeReq = {sessionStore} as any
  sessionStore.generate(fakeReq)
  Object.assign(fakeReq.session, sessionValue)
  await promisify(fakeReq.session.save).call(fakeReq.session)

 // NOTE: the 's:' and 'connect.sid' part may vary upon the version of express-session and your configuration

  const signed = `s:${signature.sign(fakeReq.sessionID, SECRET)}`
  return cookie.serialize('connect.sid', signed)
}

describe('route in app'), () => {
  it('sees sessionValue in req.session', async () => {
    const s = await createSessionCookie({foo: 1});
    await supertest(app)
      .get(THE_PATH)
      .set('cookie', [s])
      .expect(200);
  })
})

相关问题