[英]Cypress send multiple requests and doesn't allow to login
我使用的是Cypress 4.3.0
版本,在 cypress.json 文件中設置了 baseUrl = " https://tenant-demo.somesitedev.net "。 當我發送cy.request()
命令時,它正在發送多個請求(請參見圖:1)。 此外,當我觀察訪問命令時,我可以看到以下原始 Url、已解決 Url 和重定向。 在這種情況下,我如何使用cy.request()
命令登錄到站點。
before(()=>{
cy.visit('/').then(()=>{
cy.get('input[type="hidden"]').invoke('val').then((val)=>{
const token = val;
cy.login(token);
})
})
})
Cypress.Commands.add('login', (token) => {
const username= 'test1.user';
const password= 'somepassword';
const accessToken = localStorage.getItem('tokens');
const cookieValue = document.cookie.split(';');
const configCat = localStorage.getItem('ConfigCat_');
cy.request({
method: 'GET',
url: '/dashboard',
failOnStatusCode: false,
form: true,
body:{
_token: token,
username,
password
},
headers: {
'accept': 'text/html',
'content-type': 'application/x-www-form-urlencoded',
'authorization': `bearer ${accessToken}`,
'ConfigCat_': `${configCat}`,
'cookie': `${cookieValue}`
}
}).then((res)=>{
visitDashboard();
})
})
const visitDashboard = () => {
cy.visit('dashboard')
}
圖。1
圖:2
不知何故,我設法找到了解決問題的方法。 由於baseUrl
有一些路徑擴展/auth/login
,每當我觸發 cy.request() 時,即使憑據正確,它也總是重定向回登錄頁面。 控制台中還有兩個請求。
所以我的方法是在第一個帶有qs
參數的 POST cy.request() 之后立即發送另一個帶有 GET 方法的cy.request()
和body
參數。 從請求標頭中,我發現每次用戶登錄時都會提交一個“令牌”。 如果有另一種簡單的方法讓我知道。
賽普拉斯版本:4.4.0
在beforeEach()
中,獲取 'token' 值;
beforeEach(() => {
cy.visit('/');
cy.loadTokens();
cy.get('input[name="_token"]').invoke('val').then((val)=>{
const tokenValue = val;
cy.loginRequest(tokenValue);
})
})
以下是commands.js
文件:
Cypress.Commands.add('loginRequest', function (tokenValue) {
return cy.request({
method: 'POST',
url: Cypress.config('baseUrl'),
followRedirect: true,
headers: {
'content-type': 'text/html; charset=UTF-8'
},
qs:{
_token: tokenValue,
username: 'your_username',
password:'your_password'
}
}).then(()=>{
return cy.request({
method: 'GET',
url: 'https://tenant-demo.somesitedev.net/dashboard',
followRedirect: false,
headers: {
'content-type': 'text/html; charset=UTF-8'
},
body:{
_token: tokenValue,
username: 'your_username',
password:'your_password'
}
})
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.