gpt4 book ai didi

express - 如何用 Jest 测试 Passport LocalStrategy

转载 作者:行者123 更新时间:2023-11-28 21:36:37 25 4
gpt4 key购买 nike

存有 express Passport LocalStrategy 测试,可能应模拟请求。

test('should Test password Login auth', async (done) => {
const response = jest.fn((arg)=> console.log('args', arg));
const next = jest.fn();
let mockReq = {body: { username: "test@gmail.com", password: "tets"}}
let mockRes = {send: function(ats){console.log("mockResFunc", ats), response()}};

passport.authenticate('local', ()=> response())(mockReq, mockRes);

expect(next).not.toHaveBeenCalled();
expect(response).toHaveBeenCalled();

但回调从未被调用,而且我没有找到密码和用户名进入 Passport 功能。有没有人知道如何使用 Jest 来模拟凭据(我认为这是线索)?

passport.use(new LocalStrategy(
async function(username, password, done) {
const existingUser = await User.findOne({ 'email' : username })
console.log('credits', username, password, existingUser.email)
if (existingUser) {
let validUsr = existingUser.validPassword(password);
if (existingUser && validUsr) {
console.log('passport',existingUser.email)
return done(null, existingUser);
}
}
return done(null, false, { message: 'Wrong credentials.' });
}
));

最佳答案

不要为局部策略之类的东西写一个模拟函数,写一个实际的函数

const request = require('supertest')
const app = require('../server/app')
describe('Login', () => {
it('should fail with incorrect credentials', async () => {
const res = await request(app)
.post('/auth/login')
.send({
email: 'dummy',
password: 'demo'
})
expect(res.statusCode).toEqual(401)
expect(res.body).toHaveProperty('message')
})

it('should succeed with correct credentials', async () => {
const res = await request(app)
.post('/auth/login')
.send({
email: 'demo',
password: 'demo'
})
expect(res.statusCode).toEqual(200)
expect(res.body).toEqual({ email: 'demo' })
})
})

describe('Logout', () => {
it('should logout successfully', async () => {
const res = await request(app).post('/auth/logout')
expect(res.statusCode).toEqual(200)
expect(res.body).toEqual({ ok: true })
})
})

关于express - 如何用 Jest 测试 Passport LocalStrategy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58146459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com