我在功能测试中使用 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/