3 回答

TA貢獻1864條經驗 獲得超6個贊
更新:這并不可靠。我剛剛做了一些重構,看來這個解決方案也有缺陷。重定向可能發生在 cypress 訪問頁面和觸發 之間,cy.wait因此測試最終會等待已經發生的事情。下面的內容可能仍然適合您,具體取決于您的重定向何時被觸發,但如果它是在初始化時觸發的,則這似乎不起作用。
不太喜歡這個解決方案,因為重定向仍然發生(我還沒有找到取消它的方法),但它至少測試了重定向是否發生,并允許我檢查查詢:
cy.intercept({ pathname: `/sessions/new` }).as(`loginRedirect`)
cy.visit(`/dashboard/`)
cy.location().then(($location) => {
cy.wait(`@loginRedirect`).then(($interceptor) => {
const { query } = urlParse($interceptor.request.url)
expect(query).to.equal(`?token=true&redirect=${$location.href}`)
})
})
注意:在 v6 中route2更改為。intercept

TA貢獻1820條經驗 獲得超9個贊
Gleb Bahmutov 在Deal with window.location.replace中有一種方法,它window.location
在源中重命名為window.__location
有效的存根。
它用于在加載頁面到達瀏覽器之前cy.intercept()
修改加載頁面,即在實例化并成為完全不可變/不可損壞的對象之前。window.location
it('replaces', () => {
? cy.on('window:before:load', (win) => {
? ? win.__location = {? ? ? ? ? ? ? ? ? ? ? ? ? ?// set up the stub
? ? ? replace: cy.stub().as('replace')
? ? }
? })
? cy.intercept('GET', 'index.html', (req) => {? ?// catch the page as it loads
? ? req.continue(res => {
? ? ? res.body = res.body.replaceAll(
? ? ? ? 'window.location.replace', 'window.__location.replace')
? ? })
? }).as('index')
? cy.visit('index.html')
? cy.wait('@index')
? cy.contains('h1', 'First page')
? cy.get('@replace').should('have.been.calledOnceWith', 'https://www.cypress.io')
})
這個存根replace,但同樣應該適用于設置href器。

TA貢獻1793條經驗 獲得超6個贊
這是我發現的唯一方法是檢測成功的重定向客戶端(如果是第三方網站)。JavaScript 有一個方便實用的函數,稱為window.open(). 您可以用它做很多事情,包括重定向網頁。_self這可以通過將目標設置為或 來完成_top。通過使用 while 循環,您可以盡快運行代碼。這是我如何記錄客戶端重定向的草稿。
var redirectURL = 'https://www.example.com/',
redirectWindow = window.open(redirectURL, '_top'),
redirected = false,
count = 0;
while(true) {
if (redirectWindow.document.readyState === 'complete') {
redirected = true;
//Your code here. I am just logging that it is in the process of redirection.
console.log('redirecting')
break;
}
if (count > 2000) {
redirected = false;
break;
}
count++
}
if (redirected == false) {
console.log('Error: Redirect Failed');
}
添加回答
舉報