[英]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.