email.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * Helper function for opening an email in Roundcube based mailtrap.
  3. * We need to cross an origin boundary, which complicates the use of variables.
  4. * Any variables need to be explicitly defined and the "runner" may only reference these and none from its scope.
  5. * It is not possible to use Cypress helper functions, e.g. from the testing library or other functions like "activateUser", inside the "runner".
  6. * REF: https://github.com/testing-library/cypress-testing-library/issues/221
  7. */
  8. export function openEmail<T>(
  9. subject: string | RegExp,
  10. runner: (
  11. frame: Cypress.Chainable<Cypress.JQueryWithSelector<any>>,
  12. args: T
  13. ) => void,
  14. args?: T
  15. ) {
  16. const runnerS = runner.toString()
  17. cy.origin(
  18. Cypress.env('MAILTRAP_URL') || 'http://mailtrap',
  19. { args: { args, runnerS, subject } },
  20. ({ args, runnerS, subject }) => {
  21. cy.visit('/')
  22. cy.get('input[name="_user"]').type('mailtrap')
  23. cy.get('input[name="_pass"]').type('password-for-mailtrap')
  24. cy.get('button[type="submit"]').click()
  25. cy.url().then(url => {
  26. if (!url.includes('?_task=login')) return
  27. cy.log('mailtrap login is flaky in cypress, submit again')
  28. cy.get('input[name="_pass"]').type('password-for-mailtrap')
  29. cy.get('button[type="submit"]').click()
  30. })
  31. // Use force as the subject is partially hidden
  32. cy.contains(subject).click({ force: true })
  33. cy.log('wait for iframe loading')
  34. // eslint-disable-next-line cypress/no-unnecessary-waiting
  35. cy.wait(1000)
  36. cy.get('iframe[id="messagecontframe"]').then(frame => {
  37. // runnerS='(frame, args) => { runner body }'. Extract the runnable function.
  38. // eslint-disable-next-line no-new-func
  39. const runner = new Function('return ' + runnerS)()
  40. runner(cy.wrap(frame.prop('contentWindow').document.body), args)
  41. })
  42. }
  43. )
  44. }