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

问题描述

我在功能测试中使用 Cypress 拦截我的登录和注销路由。 (我必须存根它们,因为我用于身份验证的 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。登录路由的存根工作完美。但是,登录路由的存根没有。

原来的注销路径是这样的:

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();
};

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

解决方法

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

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

这是错误

赛普拉斯错误

Cypress 检测到您从命令返回了一个承诺,同时还调用了该承诺中的一个或多个 cy 命令。

你在 promise 中调用的 cy 命令是:cy.clearCookie()

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

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

虽然它是一个内部命令,但它的使用已经在 Cypress AutomationTesting 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)
  })
})

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...