The 'cookies' property is not defined in the 'undefined' type

I am working on incorporating Google's Sign-In for Cypress tests using the following plugin: https://github.com/lirantal/cypress-social-logins/ (I am utilizing TypeScript). The code I have implemented is as follows:

it('Login through Google', () => {
const username = Cypress.env('googleSocialLoginUsername')
const password = Cypress.env('googleSocialLoginPassword')
const loginUrl = Cypress.env('loginUrl')
const cookieName = Cypress.env('cookieName')
const socialLoginOptions = {
  username,
  password,
  loginUrl,
  headless: false,
  isPopup: true,
  logs: false,
  loginSelector: 'a[href="/auth/auth0/google-oauth2"]',
  postLoginSelector: '.account-panel'
}

return cy.task('GoogleSocialLogin', socialLoginOptions).then(({cookies}) => {
  cy.clearCookies()

  const cookie = cookies.filter((cookie: { name: any; }) => cookie.name === cookieName).pop()
  if (cookie) {
    cy.setCookie(cookie.name, cookie.value, {
      domain: cookie.domain,
      expiry: cookie.expires,
      httpOnly: cookie.httpOnly,
      path: cookie.path,
      secure: cookie.secure
    })

    Cypress.Cookies.defaults({
      whitelist: cookieName
    })
  }
})
});

The error message I encountered was:

Property 'cookies' does not exist on type 'undefined'.ts(2339)

Do you have any suggestions on how to resolve this issue?

Answer №1

Resolution

Take a look at this code snippet:

Cypress.on('window:before:load', (win) => {
  // This function is called before any scripts are loaded, so the ga function needs to be defined.
  (<any>win).gapi = cy.stub().as('gapi')
  win.gapi = {
    load(){
      return null;
    },
    auth2: {
      authorize({}, callback){
        callback( {id_token: 'example'} );
      },
    }
}})

const login = () => {
  cy.getCookies().should('be.empty');
  cy.visit('/');
  cy.title()
    .should('equal', 'Solution Catalog and Costing Tool')
    .pause();

  cy.fixture('user').as('loginApiResponse');
  cy.fixture('projects').as('initialProjects');
  cy.fixture('account').as('getAccount');

  cy.server();

  cy.route({
    method: 'POST',
    url: '**/api/*/login',
    status: 200,
    response: '@loginApiResponse',
    delay: 500,
  }).as('getUser');

  cy.route({
    method: 'GET',
    url: '**/api/*/account',
    status: 200,
    response: '@getAccount',
    delay: 500,
  }).as('getAccount');

  cy.route({
    method: 'GET',
    url: '**/api/*/estimates?limit=10&offset=0',
    status: 200,
    response: '@initialProjects',
    delay: 500
  });

  cy.get('[data-cy=GoogleButton]')
    .click()
    .should('be.disabled');

  cy.checkReduxState('login', 'loginInProgress');

  cy.wait('@getUser');

  cy.url().should('include', '/estimates');

  cy.fixture('user').then(user => {
    cy.checkReduxState('login', 'user', user);
  });
};

Cypress.Commands.add('login', () => login());
Cypress.Commands.add('checkReduxState', (store, name, data) => checkReduxState(store, name, data));
Cypress.Commands.add('waitForResource', (name, options = {}) => waitForResource(name, options));
Cypress.Commands.overwrite('visit', (originalFn, url, options) =>
  overwriteFetch(originalFn, url, options),
);

For more information and documentation on this issue, you can refer to https://github.com/cypress-io/cypress-example-recipes/tree/master/examples/stubbing-spying__google-analytics.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is Operator Overloading supported in Typescript?

I'm curious about whether operator overloading is supported in typescript. If it does exist, I'd be happy to provide an example or a link for you to explore further. ...

Utilize React Hook Form to easily reset the value of an MUI Select component

I created a dropdown menu where users can select from "Item 1", "Item 2", and "Item 3". Additionally, there is a "Reset" button that allows users to clear their selection and make a new one. Below is the code I used: import React from ...

What could be causing the issue with dayjs dynamic importing in TypeScript?

Currently, I am developing a web screen within a .NET application and facing an issue with sending datetime preferences from the system to the web screen using CefSharp settings. AcceptLanguageList = CultureInfo.CurrentUICulture.Name In my TypeScript code ...

Leverage the power of TypeScript custom transformer and project reference for enhanced

I am currently working on a project that involves using both project references and custom transformers. The issue I am facing is that project references require the use of TSC for incremental compilation, but when TSC is used, the transformers are not app ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...

Is there a way to remove the old React component when there are two instances of it still active while passing variables?

Recently, I've encountered some unusual behavior with my React component. As a newcomer to React, I have a page where users can configure toast notifications that are displayed. For this functionality, I'm utilizing the react-hot-toast package. U ...

Creating a factory function through typhography

I have a dynamically generated list of functions that take an argument and return different values: actions: [ param => ({name: param, value: 2}), param => ({label: param, quantity: 4}), ] Now I am looking to create a function that will gen ...

Having trouble accessing the theme in a styled component with @emotion/styled

https://i.stack.imgur.com/zHLON.png I've been using @emotion/react for theming and successfully injected the theme into it. I can access the theme using useTheme within components, but I'm facing some difficulties in accessing the theme within s ...

Can a VS Code theme extension be designed using JavaScript or TypeScript rather than JSON?

Currently working on a VS Code theme extension, I am interested in exploring the possibility of using JavaScript or TypeScript files instead of a JSON file. The idea of having all the theme information crammed into one massive JSON file feels disorganize ...

Struggling with continuously re-rendering a color background when using useMemo in React?

After every re-render, a new color is generated. Is there a way to store the initial color and reuse it in subsequent renders? const initialColor = generateNewColor(); // some random color const backgroundColor = React.useMemo(() => { return ...

What could be causing the service method in the controller not to be called by Node JS?

In my current Node JS project, the folder structure of my app is as follows: src │ index.js # Main entry point for application └───config # Contains application environment variables and secrets └───controllers # Hou ...

Module 'next-intl/client' cannot be located

When I run npm test, I encounter the following error: 'next-intl/client' module not found jest.mock( | ^ 22 | 'next-intl/client', 23 | (): Record<string, unknown> => ({ 24 | usePathname: ...

Decide whether to fulfill or deny a Promise at a later time in

When working on an Angular2/TypeScript project, a dialog is shown and the system returns a Promise object to the caller. This Promise will be resolved after the user closes the dialog. The interface of the Promise class does not include methods like resol ...

Ionic causing delay in updating ngModel value in Angular 2

My ion-searchbar is set up like this: <ion-searchbar [(ngModel)]="searchQuery" (keyup.enter)="search();"></ion-searchbar> In the typescript file, the searchQuery variable is defined as follows: export class SearchPage { searchQuery: string ...

Configuring TypeScript to utilize worker_threads

Currently, I am attempting to implement WebWorkers in my Typescript project and I have encountered a hurdle. Despite having installed @types/node and updating everything, 'worker_threads' has transitioned from an experimental feature to a stable ...

Unable to set textAlign column property in Inovua React Data Grid using typescript

I am currently facing an issue with centering the content of each grid cell in Inovua RDG. A frustrating TypeScript error keeps popping up: Type '{ name: string; header: string; textAlign: string; defaultFlex: number; defaultVisible?: undefined; }&apo ...

The Ionic framework has a defined variable

In my code, I have initialized a variable inside the constructor like this: constructor(public http: HttpClient) { this.data = null; this.http.get(this.url).subscribe((datas: any) => { this.dbUrl = datas[0].db_url2; console.log(this ...

Leveraging private members in Typescript with Module Augmentation

Recently, I delved into the concept of Module Augmentation in Typescript. My goal was to create a module that could inject a method into an object prototype (specifically a class) from another module upon import. Here is the structure of my folders: . ├ ...

Is it possible to eliminate the arrows from an input type while restricting the change to a specific component?

Is there a way to remove the arrows from my input field while still applying it only to the text fields within this component? <v-text-field class="inputPrice" type="number" v-model="$data._value" @change="send ...

What is the reason for Cypress choosing to omit specific commands?

The test below aims to scan and authenticate a QR code, then utilize the received authentication token. However, for some reason, the last two commands (.type) are not being executed. I've been stuck at this point for quite some time now. Any insights ...