我正在嘗試使用兩個具有不同回應的 cy.intercept 函式來存根相同的 http GET 請求。我嘗試這樣做的一種方法是使用條件 if 陳述句。在 if 陳述句中,我會呼叫 cy.intercept 函式。我使用了一個布爾變數作為條件。問題是布爾變數不會根據測驗場景而改變(我將 cypress 與 cypress-cucumber-preprocessor 一起使用)。如何實作我的測驗檔案,使其根據測驗將條件定義為真或假,從而動態定義不同的 cy.intercept 回應?
我的測驗檔案:
let isValid = false
Given('I am on the "user-login" page', () => {
cy.log(isValid)
cy.visit("http://localhost:8080/user-login")
cy.title().should('eq',"User Login Page")
isValid = true
cy.log(isValid)
})
Given('I am on the "user-login" page', () => {
cy.log(isValid)
cy.visit("http://localhost:8080/user-login")
cy.title().should('eq',"User Login Page")
isValid = false
cy.log(isValid)
})
When('I enter "George312"', () => {
cy.get('input[type="text"]').should("be.visible").type("George312")
})
When('I enter "George312"', () => {
cy.get('input[type="text"]').should("be.visible").type("George312")
})
And('I enter "hsj%2*sc5$"', () => {
cy.get('input[type="password"]').should("be.visible").type("hsj%2*sc5$")
})
And('I enter "hsj%2*sc5$3"', () => {
cy.get('input[type="password"]').should("be.visible").type("hsj%2*sc5$3")
})
And('I Click the "Submit" button', () => {
if(isValid === true){
cy.intercept('api/users',
{
"body": { "isAuthenticated": true}
}
).as("loginUser")
}
cy.get('button[id="LoginBtn"]').should('be.visible').click()
cy.wait(2000)
cy.wait("@loginUser")
})
And('I Click the "Submit" button', () => {
isValid = false
if(isValid === false){
cy.intercept('api/users',
{
"body": { "isAuthenticated": false}
}
).as("loginUser")
}
cy.get('button[id="LoginBtn"]').should('be.visible').click()
cy.wait(2000)
cy.wait("@loginUser")
})
Then('I should see written in a window user "George312 is now logged in!"', () => {
cy.get("p").contains('user "George312 is now logged in!"').should("be.visible")
})
Then('I should see written in a window user "Login Failed! wrong password"', () => {
cy.get("modal").contains("Login Failed! wrong password").should("be.visible")
})
cy.log() 就像 console.log()。我在我的代碼中用紅色表示了 cy.log() 的四個呼叫的輸出。輸出沒有意義這是賽普拉斯的輸出:

cy.log() 就像 console.log()。我在我的代碼中用紅色表示了 cy.log() 的四個呼叫的輸出。輸出沒有意義。就好像變數設定為 true 并且此后永遠不會更改。
uj5u.com熱心網友回復:
我找到了解決辦法。我宣告的變數必須以這種方式宣告:
this.isValid
因此可以在檔案中的其他位置訪問它。其次: Given() 陳述句應該彼此不同。否則,這兩種情況都會在兩種情況下激活,導致變數值在最后一次初始化中被覆寫。
像這樣:
Given(/^I am on the "user-login" 1 page$/, () => {
cy.visit("http://localhost:8080/user-login")
cy.title().should('eq',"User Login Page")
this.isValid = true
cy.log(this.isValid)
})
Given(/^I am on the "user-login" page$/, () => {
cy.log(this.isValid)
cy.visit("http://localhost:8080/user-login")
cy.title().should('eq',"User Login Page")
this.isValid = false
cy.log(this.isValid)
})
然后cypress輸出變成這樣:

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/386964.html
