Home > database >  How to check the value of a cookie Testcafe & JS?
How to check the value of a cookie Testcafe & JS?

Time:10-05

For the purpose of an automated test I need to write a piece of Javascript/Typescript code that on a given website, after giving consent to all cookie, will check two things:

  • the presence of a specific cookie (I know the name of this cookie)
  • the value of this specific cookie

I started like below but have no idea how to go further:

import { Selector, RequestLogger, ClientFunction } from 'testcafe';
const getValueOfCookie = ClientFunction(() => document.cookie)
... ?

Is anyone able to help me with it?

CodePudding user response:

Since document.cookie is a string, you have to parse it in order to check for the desired cookie and/or get its value.

The following code will return undefined if the cookie does not exist:

const getValueOfCookie = ClientFunction(() => {
  return document.cookie
    .split('; ')
    .find(row => row.startsWith('cookieName='))
    ?.split('=')[1];
});

See https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie for more information.

  • Related