【问题标题】:How can I clear cookies between every test using Jest and Supertest?如何使用 Jest 和 Supertest 在每次测试之间清除 cookie?
【发布时间】:2019-02-11 22:52:14
【问题描述】:

我有一套测试,如果它们单独运行,它们都会通过。但是,如果并行运行,测试会因检查 cookie 的值而失败。

问题是supertest的cookie在每次测试之间都没有清除。

有没有办法在使用 supertest 的每个测试之间清除 cookie?这与不提供解决方案的this open issue 有关。

我都试过了:

afterEach(() => {
  request(app)
    .set('Cookie', [])
})

和:

afterEach(() => {
  request(app)
    .set('Cookie', '')
})

...无济于事。

以下是两个单独运行良好但并行运行失败的测试:

test('It should respond 302 to the wrong url', (done) => {
  const accessiblePages = {get_member_accessible_pages: []}
  nock('http://localhost:8000')
    .log(console.log)
    .get('/auth/me/')
    .reply(200, accessiblePages)
  // Must use j: to work with cookie parser
  const cookie = 'userInfo=j:' + encodeURIComponent(
    JSON.stringify(accessiblePages))
  request(app)
    .get('/first-url')
    .set('Cookie', cookie)
    .expect(302)
    .expect('Location', '/new-url')
    .then((response) => {
      expect(response.statusCode).toBe(302)
      done()
    })
})

test('It should set an updated cookie for the logged in user', (done) => {
  const accessiblePages = {get_member_accessible_pages: [123, 456]}
  nock('http://localhost:8000')
    .log(console.log)
    .get('/auth/me/')
    .reply(200, accessiblePages)
  // Must use j: to work with cookie parser
  const userInfoCookie = 'userInfo=j:' + encodeURIComponent(
    JSON.stringify(accessiblePages))
  const accessTokenCookie = 'accessToken=accessToken'
  const requestCookie = [userInfoCookie, accessTokenCookie].join(';')
  const responseCookieValue = accessiblePages
  request(app)
    .get('/first-url')
    .set('Cookie', requestCookie)
    .expect(200)
    .then((response) => {
      expect(response.statusCode).toBe(200)
      const cookies = setCookie.parse(response)
      expect(cookieParser.JSONCookie(cookies[0].value))
        .toEqual(responseCookieValue) // FAILS HERE - shows accessiblePages variable from the previous test.
      done()
    })
})

【问题讨论】:

  • @KaiserKatze 这不是 jQuery - 它是一个名为 jquery-cookie 的 jQuery 插件。我不想添加两个我不需要的第三方库,只是为了让我的测试正常工作。
  • @KaiserKatze 另外 - Jest 与传统的 DOM 有点不同。例如,使用this answer 也不起作用。

标签: reactjs jestjs supertest superagent


【解决方案1】:

您可以尝试明确清除您在测试中设置的 cookie。 它可以通过 NPM 模块 'js-cookies' 或通过简单的辅助函数来完成:

function removeCookie(name) {
  document.cookie = `${name}=1; expires=1 Jan 1970 00:00:00 GMT;`
}

如果您想一次清除所有 cookie,您可以使用this 解决方案。

【讨论】:

    猜你喜欢
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2020-05-26
    • 2021-08-15
    • 2021-09-01
    相关资源
    最近更新 更多