簡體   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