繁体   English   中英

如何使用 Cypress 测试外部依赖的组件

[英]How to test components that external dependencies with Cypress

我正在尝试借助赛普拉斯的新组件测试功能来测试谷歌地图组件。

我面临的问题是我正在努力将谷歌地图附加到页面上。

目前,组件有一个启动器方法,它将谷歌地图挂载到标题,在正常加载页面时效果很好,但它在赛普拉斯测试中不起作用。

有没有一个例子可以说明如何实现相似?

示例测试文件,我所做的就是:

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

要加载我使用的谷歌地图:

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

document.head.appendChild(script);

看起来您遵循了这些文档加载 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);

要在 Cypress 组件测试中进行复制,请对 Cypress 应用程序窗口/文档执行类似操作
(这个没试过)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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