Home > Software engineering >  Cypress: login through magic link error with cy.origin()
Cypress: login through magic link error with cy.origin()

Time:10-13

Devs at my startup have switched login to a magic link system, in which you get inside after clicking a link on the email body.

I have set up a Mailsac email to receive mails containing magic links but I haven't been able to actually follow those links because of the following:

enter image description here

cy.request({
  method: "GET",
  url: "https://mailsac.com/api/addresses/[email protected]/messages",
  headers: {
    "Mailsac-Key": "here-goes-the-key",
  },
}).then((res) => {
  const magicLink = res.body[0].links[0];
  cy.origin(magicLink, () => {
    cy.visit('/')
  });
});

I wasn't able to use cy.visit() either because the magic link URL is slightly different from the baseURL in this testing environment.

So my question is: How could I follow this cumbersome link to find myself logged in home, or else, is there another way to deal with magic links?

Thanks

CodePudding user response:

The docs say

A URL specifying the secondary origin in which the callback is to be executed. This should at the very least contain a hostname, and may also include the protocol, port number & path. Query params are not supported.

Not sure if this means the cy.visit() argument should not have query params, of just the cy.origin() parameter.

Try passing in the link

cy.request({
  ...
}).then((res) => {
  const magicLink = res.body[0].links[0];
  const magicOrigin = new URL(magicLink).origin
  cy.origin(magicOrigin, { args: { magicLink } }, ({ magicLink }) => {
    cy.visit(magicLink)
  });
});

If that doesn't fix it, you could try using cy.request() but you'll have to observe where the token is stored after using the magicLink.

cy.request({
  ...
}).then((res) => {
  const magicLink = res.body[0].links[0];
  cy.request(magicLink).then(response =>
    const token = response???   // find out where the auth token ends up
    cy.setCookie(name, value)   // for example
  });
});

CodePudding user response:

You need to pass the domain as the first parameter to origin, and do the visit within the callback function, something like this:

cy.origin(magicLinkDomain, () => {
    cy.visit(magicLink);
    //...
})

Reference: https://docs.cypress.io/api/commands/origin#Usage

  • Related