![](/img/trans.png)
[英]How can I use cy.intercept to stub two requests of the same name but return two different bodies?
[英]how to stub two requests with differents stubs using cy.intercept()?
我正在嘗試使用兩個具有不同響應的 cy.intercept 函數來存根相同的 http GET 請求。 我嘗試這樣做的一種方法是使用條件 if 語句。 在 if 語句中,我將調用 cy.intercept function。 我使用 boolean 變量作為條件。 問題是 boolean 變量不會根據測試場景而改變(我正在使用帶有 cypress-cucumber-preprocessor 的 cypress)。 如何實現我的測試文件,使其根據測試將條件定義為真或假,從而動態定義不同的 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() 的四個調用的 output。 output 不做 sen 這里是 cypress 的 output:
cy.log() 就像 console.log()。 我在我的代碼中用紅色表示了 cy.log() 的四個調用的 output。 output 沒有意義。 就好像變量被設置為 true 並且之后永遠不會改變。
我找到了解決方案。 我要聲明的變量必須以這種方式聲明: 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 output 變成這樣:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.