【问题标题】:Cookie value is empty after navigating to second page导航到第二页后 Cookie 值为空
【发布时间】:2022-01-19 12:58:44
【问题描述】:

我有 2 个域。对第一个执行的某些操作会导致在它们两个上设置相同的 cookie。我需要在两个域上读取此 cookie 的值。问题是,然而这在第一个是可能的,在导航到第二个之后,cookie 是存在的,但它的值是空的。

为什么?

获取 cookie 值的代码如下:

const getCookie = ClientFunction(() => {
    const name = 'ConfigCookie';
    const match = document.cookie.match(new RegExp(name + '=([^;]+)'));
    let decodedValue;
    if (match) decodedValue = decodeURIComponent(match[1]).replace(/%28/g, '(').replace(/%29/g, ')');
    return JSON.parse(decodedValue || '');
})

这是测试代码(我删除了敏感数据)

test('xyz', async t => {
    await t
        .navigateTo(FirstDomain)
        .click(firstDomainSubmitButtonSelector)
        const firstDomainCookie = await getCookie();
        const firstDomainConsents = firstDomainCookie.consents;
    await t
        .expect(consents).eql({here the expected value});
    await t
        .navigateTo(SecondDomain)
        const secondDomainCookie = await getCookie();
        const secondDomainConsents = secondDomainCookie.consents;
        console.log(secondDomainConsents)
})

【问题讨论】:

  • 据我记得它与安全相关,例如 JS 只能从其运行的域/站点读取 cookie 信息。否则任何恶意代码都可以读取任何内容的 cookie 内容

标签: typescript testing cookies automated-tests testcafe


【解决方案1】:

我创建了一个带有 TestCafe 测试的代码 sn-p,显示了您描述的行为。我这边的测试是绿色的。您能否更改测试以显示有问题的行为并分享更正测试的代码,以便我可以重现该问题?

import { Selector, ClientFunction } from 'testcafe';
 
fixture`test fixture`
const FirstDomain = 'http://devexpress.github.io/testcafe/example';
const SecondDomain = 'https://wikipedia.org/';
test('test name', async t => {
    const setCookie = ClientFunction(() => {
        document.cookie = 'key=value'
    });
    const getCookie = ClientFunction(() => {
        return document.cookie;
    });
    const data = 'key=value'
    await t.navigateTo(FirstDomain)
    await setCookie()
    await t.expect(await getCookie(data)).ok()
    await t.navigateTo(SecondDomain)
    await setCookie()
    await t.expect(await getCookie()).ok(data)
    await t.navigateTo(FirstDomain).click(await Selector('#submit-button'))
    await t.expect(await getCookie()).ok(data)
    await t.navigateTo(SecondDomain)
    await t.expect(await getCookie()).ok(data)
})

【讨论】:

  • 感谢德米特里的回答。在您提供的 sn-p 中,我看到您首先设置 cookie,然后读取它。我的问题是我不需要设置 cookie。 cookie 由我们的前端库在这两个域上设置(由对第一个域执行的某些操作触发)。当我在调试器模式下调试测试时,我可以看到确实在两个域上都设置了 cookie,但是这个 cookie 的值只存在于第一个域上。我读过这可能与CORS有关。另外,也许这个 cookie 是 SameSite-Lax 的事实在这里有什么用?
  • 克劳迪娅,谢谢你的详细解释。不幸的是,如果不在我身边复制它,我无法帮助您解决这个问题。您能否分享任何证明问题的测试?如果问题与 TestCafe 框架有关,我会尽力提供帮助。
猜你喜欢
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多