简体   繁体   中英

Cypress: Add cookie to external api calls from localhost frontend

I have an external api deployed to a dev server and a frontend app running on localhost . I need to attach the cookies I get from logging in, to both my localhost and external API domain.

I can see the cookies are indeed there using cy.getCookies({domain: null}) , however all external API calls within the react app happen without the cookies. From what I can see, you can only add cookies to the baseUrl requests, but I want to run my tests against a deployed backend (so developers don't need to have a running instance of a local backend, which is whats currently working fine as they are both on localhost)

cy.setCookies(name, value, {domain: localhost}) 
cy.setCookies(name, value, {domain: external_api_domain}) 

If there is a request originating from the app to the back-end that needs a specific cookie attached, maybe an intercept can attach them.

This is untested & on-the-fly code, may need adjusting

cy.intercept('POST', my-url, (req) => 
  const cookie = cy.getCookies(name).then((cookie) => {
    req.headers['Cookie'] = `${cookie.name}=${cookie.value}`;
    req.continue()
  })
})

Assumptions

I'm assuming the frontend initiates the request that the backend then passes on to another server, and backend gets all info (including cookies) from the frontend request.

Debugging

You can check the backend phase is working with cy.request() . Ultimately you want FE to do it, but in case the problem lie in the FE and not the test cy.request() can be useful.

For ref Cypress request and cookies

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM