javascript - Cypress:删除所有拦截路由的 cookie

标签 javascript cookies cypress sinon stubbing

我在功能测试中使用 Cypress 拦截我的登录和注销路由。 (我必须对它们进行 stub ,因为我用于身份验证的 Magic 技术尚不支持服务器端 SDK 的测试模式。)

以下是路线代码:

import {
  loginRoute,
  logoutRoute,
} from 'features/user-authentication/user-authentication-api';

// ...

cy.intercept(loginRoute, request => {
  request.reply({
    headers: {
      'Set-Cookie': `magic-auth-token=${Cypress.env(
        'validMagicAuthToken',
      )}`,
    },
    statusCode: 200,
    body: { success: true },
  });
});

cy.intercept(logoutRoute, request => {
  request.reply({
    headers: {
      'Set-Cookie': `magic-auth-token=; Max-Age=-1; Path=/`,
    },
    statusCode: 302,
  });
});

我正在模仿原始路由的行为,其中添加和删除 cookie。登录路由的 stub 工作完美。但是,登录路由的 stub 则不然。

原始的注销路线如下所示:

import { parse, serialize } from 'cookie';

// ...

function removeTokenCookie<T>(response: NextApiResponse<T>) {
  const cookie = serialize(TOKEN_NAME, '', {
    maxAge: -1,
    path: '/',
  });

  response.setHeader('Set-Cookie', cookie);
}

const logoutHandler: NextApiHandler = async (request, response) => {
  const session = await getSession(request);

  if (session) {
    await magic.users.logoutByIssuer(session.issuer);
  }

  removeTokenCookie(response);
  response.writeHead(302, { Location: '/' });
  response.end();
};

如何使用注销路由的 stub 删除 cookie?由于某种原因,当我像上面那样设置 header 时,cookie 不会被删除。

最佳答案

Cypress 拥有 clearCookie command ,但不能在拦截回调内部使用。

cy.intercept(logoutRoute, request => {
  cy.clearCookie('magic-auth-token')
  request.reply...
})

这是错误

CypressError

Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise.

The cy command you invoked inside the promise was: cy.clearCookie()

查看clearCookie的源码,归结为内部命令

Cypress.automation('clear:cookie', { name: <cookie-name> })

虽然这是一个内部命令,但它的使用已在此处进行了演示 Cypress Automation在这里Testing an Application in Offline Network Mode

最近添加了类型定义 Add type for Cypress.automation #7573

这是一个概念证明,

it('clears cookies in intercept', () => {

  cy.setCookie('magic-auth-token', '1234')
  cy.getCookies().should('have.length', 1)

  cy.intercept('*', (req) => {
    Cypress.automation('clear:cookie', { name: 'magic-auth-token' })
  })

  cy.visit('http://example.com').then(() => {
    // after the request has been intercepted
    cy.getCookies().should('have.length', 0)
  })
})

关于javascript - Cypress:删除所有拦截路由的 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68055786/

相关文章:

javascript - 在 Javascript 中从 math.matrix 获取元素

angularjs - 使用 CSRF_COOKIE_HTTPONLY 将 Django CSRF token 传递给 Angular

Cypress.io - sitemap.xml 验证测试

angular - Cypress 测试 - Google Places 自动完成功能不工作

javascript - 使用 AJAX 发送用户 POST 输入

javascript - 使用 HTML5 文件上传 API 的可恢复上传 -

javascript - 获取缩放图像的原始大小

PHPSESSID 未保存到 cookie

java - Spring 4 Session Cookie 更改字段

javascript - Cypress Js Testing 将 DOM 的内容与其之前的值进行比较