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

时间:2021-06-20 12:22:00

标签: javascript cookies cypress sinon stubbing

我在功能测试中使用 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 不会被删除。

1 个答案:

答案 0 :(得分:5)

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