赛普拉斯:删除所有带有拦截路由的cookie

Cypress: remove all cookies with intercepted route

我正在使用 Cypress. (I have to stub them because the 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?出于某种原因,当我像上面那样设置 headers 时,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 and here 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)
  })
})