node.js - 无法再次使用 Jest、Supertest、Passport、Koa2 在测试中发送经过身份验证的请求

标签 node.js jestjs supertest koa2

我一直在尝试使用 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/

相关文章:

javascript - 使用异步 js 迭代数组并在回调中执行函数以返回单个结果

javascript - 获取服务器上选项卡的套接字实例

javascript - 如何使用 CSRF 测试 express form post?

node.js - 在编写使用 supertest 的测试时访问 req.session 对象

mysql - 当 apache mysql 发生更改时触发 node.js

node.js - 使用 Redis 存储索引索引的最佳方式?

javascript - Jest : Specific selector

jestjs - 在 Jest 中有条件地运行测试

javascript - 为 Jest 的每个测试文件指定 window.location

node.js - 在 typescript 上扩展 super 测试