如何使用处理函数返回window.location.pathname在柏树?



我有一些函数返回windows.location。pathname,然后对这个函数进行变换并根据结果进行一些数据转换,但当我运行柏树测试时我得到一些柏树对象,所以如果我想使用window。location。pathname我应该如何处理它在柏树(e2e测试)

const getLocaleBeforeFlowsLoaded = (location = history.history.location) => {
const locale = location.pathname.split('/')[1]
// get error here since we have "__cypress" instead of locale above
const priceFormatter = new Intl.NumberFormat(locale, {
currencyDisplay: 'symbol',
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 0,
})

return priceFormatter
}

我想这是因为柏树还没有准备好,因为在其他地方它工作得很好,它只是在应用程序启动之前启动的函数

看起来您从错误的窗口获取了位置。

history变量为您提供了测试运行器位置(因此URL中的__cypress),但测试中的应用程序处于<iframe>中,因此它具有不同的全局window,location等集。

试试这个

const getLocaleBeforeFlowsLoaded = (location) => {
const locale = location.pathname.split('/')[1]
const priceFormatter = new Intl.NumberFormat(locale, {
currencyDisplay: 'symbol',
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 0,
})

return priceFormatter
}
cy.visit(...)
cy.location().then(location => {
const priceFormatter = getLocaleBeforeFlowsLoaded(location)
...
})

基于cypress文档:

cy.location() // Get location object
cy.location('pathname') // Get the path name of the location object
cy.location('port') // Get the port of the location object
...