我一直在尝试使用 internetross 的 March 2018 answer无济于事。我也在使用 Jest、Supertest,在我的例子中是 Koa 和 Passport。
在 Visual Studio 中使用 REST 客户端,没问题。 session 通过,Passport 进行身份验证,然后我获得数据。但是在 Jest 中,不行。我可以正常登录,我可以正常使用 Koa:sess,但我无法发出经过身份验证的请求。
有人看到下面的东西吗?
const supertest = require('supertest')
const app = require('../app.js')
const http = require('http')
const agent = supertest.agent((http.createServer(app.callback())))
let session = null
beforeAll(async () => {
const response = await agent
.post('/v1/users/login')
.set({'content-Type': 'application/json'})
.send({ username: 'username', password: 'password' })
session = response.headers['set-cookie'][0]
.split(',')
.map(item => item.split(';')[0])
.join('; ')
console.log(stringify(session))
expect(response.status).toEqual(200)
})
describe('user tests', () => {
test('data', async () => {
const response = await agent.get('/v1/users/data?dataIdId=140934')
.set('Cookie', session)
expect(response.status).toEqual(200)
})
})
当然,另一个问题是,如果您使用代理,为什么这是必要的。但我在这方面也没有取得任何进展。
提前致谢。
最佳答案
经过大量调查,我终于找到了答案。由 https://github.com/facebook/jest/issues/3547#issuecomment-397183207 提供.
我不得不更换
session = response.headers['set-cookie'][0]
.split(',')
.map(item => item.split(';')[0])
.join('; ')
与
response.headers['set-cookie'][0]
.split(',')
.map(item => item.split(';')[0])
.forEach(c => agent.jar.setCookie(c));
长叹一声。
关于node.js - 无法再次使用 Jest、Supertest、Passport、Koa2 在测试中发送经过身份验证的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56685260/