0

I am trying to test a google maps components with help of Cypress's new component testing functionality.

The issue that I am faced with is that I am struggling to attach google maps to the page.

Currently, component has an initiator method which mounts google maps to the header, which works great when loading a page as normal, but it doesn't work within Cypress test.

Is there an example of how similar can be achieve?

Example test file, all I did was:

it('...', () => {
   mount(myComponent)
});

To load google maps I use:

let script = document.createElement("script");
script.src = url;

document.head.appendChild(script);
Vlad Vladimir Hercules
  • 1,781
  • 2
  • 20
  • 37

1 Answers1

2

Looks like you followed these docs Loading the Maps JavaScript API

// Create the script tag, set the appropriate attributes
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap';
script.async = true;

// Attach your callback function to the `window` object
window.initMap = function() {
  // JS API is loaded and available
};

// Append the 'script' element to 'head'
document.head.appendChild(script);

To replicate in Cypress component test, do similar thing with Cypress app window/document
(have not tried this)

const win = cy.state('window')
const document = win.document

var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap';
script.async = true;
document.head.appendChild(script);

// use attachTo option to put your component in correct context 
// i.e where google maps is global
const wrapper = mount(MyComponent, {
  attachTo: win                
})
user16695029
  • 3,365
  • 5
  • 21
  • I am facing the same trouble,but I have cypress project separated from the one to test; is there a way to achieve the same result? I am getting mad on it – Don Diego Dec 11 '21 at 08:27