![](/img/trans.png)
[英]Cypress: Can I stub/mock the window.location.hostname in a test?
[英]In a Cypress test how can I stub argument of a function
我對 gtag 了解不多,但如果您使用該頁面上顯示的“外部”function 模式而不是上面的“內聯”function 模式,那么查看參考頁面可能會存根。
在 React 或其他框架中存根內部函數的方法是將其暴露在window
object 上。
function implementExperimentA(value) {
if (value == '0') {
// Provide code for visitors in the original.
} else if (value == '1') {
// Provide code for visitors in first variant.
} else if (value == '2') {
// Provide code for visitors in section variant.
}
...
}
if (window.Cypress) {
// Cypress is active
console.log('referencing "implementExperimentA" on window')
window.implementExperimentA = implementExperimentA;
}
gtag('event', 'optimize.callback', {
name: '<experiment_id_A>',
callback: implementExperimentA
})
然后在測試中,您可以在 beforeLoad 事件中設置存根
cy.visit('http://localhost:3000', {
onBeforeLoad(win) {
// Stub your functions here
cy.stub(win, 'implementExperimentA').callsFake((realValue) => {
const mockValue = 'abc'
console.log(`implementExperimentA called with ${realValue}, subbing ${mockValue}`)
return window.implementExperimentA(mockValue)
})
},
})
這應該在頁面加載的最早點實例化存根,前提是已經設置了引用。
檢查 console.logs 是否以正確的順序觸發,如果不是,則引用 function 可能會延遲,您可以使用cy.window()
選擇存根點。
cy.visit('http://localhost:3000')
...
cy.window().then(win => {
// Stub your functions here
cy.stub(win, 'implementExperimentA').callsFake((realValue) => {
const mockValue = 'abc'
console.log(`implementExperimentA called with ${realValue}, subbing ${mockValue}`)
return window.implementExperimentA(mockValue)
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.