Home > other >  How to test components that external dependencies with Cypress
How to test components that external dependencies with Cypress

Time:10-15

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);

CodePudding user response:

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                
})
  • Related