3 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
更新:這并不可靠。我剛剛做了一些重構(gòu),看來這個(gè)解決方案也有缺陷。重定向可能發(fā)生在 cypress 訪問頁面和觸發(fā) 之間,cy.wait因此測試最終會(huì)等待已經(jīng)發(fā)生的事情。下面的內(nèi)容可能仍然適合您,具體取決于您的重定向何時(shí)被觸發(fā),但如果它是在初始化時(shí)觸發(fā)的,則這似乎不起作用。
不太喜歡這個(gè)解決方案,因?yàn)橹囟ㄏ蛉匀话l(fā)生(我還沒有找到取消它的方法),但它至少測試了重定向是否發(fā)生,并允許我檢查查詢:
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貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
Gleb Bahmutov 在Deal with window.location.replace中有一種方法,它window.location
在源中重命名為window.__location
有效的存根。
它用于在加載頁面到達(dá)瀏覽器之前cy.intercept()
修改加載頁面,即在實(shí)例化并成為完全不可變/不可損壞的對象之前。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')
})
這個(gè)存根replace,但同樣應(yīng)該適用于設(shè)置href器。

TA貢獻(xiàn)1793條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是我發(fā)現(xiàn)的唯一方法是檢測成功的重定向客戶端(如果是第三方網(wǎng)站)。JavaScript 有一個(gè)方便實(shí)用的函數(shù),稱為window.open(). 您可以用它做很多事情,包括重定向網(wǎng)頁。_self這可以通過將目標(biāo)設(shè)置為或 來完成_top。通過使用 while 循環(huán),您可以盡快運(yùn)行代碼。這是我如何記錄客戶端重定向的草稿。
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');
}
添加回答
舉報(bào)