无法使用 Cypress 发送 POST 登录请求
Unable to send a POST login request using Cypress
我正在使用 Cypress 为网站编写端到端测试,并想发出 API POST 请求来验证用户。
我已经能够发出一个请求,发送回一个带有适当 jwt 的 200 响应代码。
这是请求的代码片段:
Cypress.Commands.add('login', () => {
cy.request({
method: 'POST',
url: 'https://api.website.com/api/login',
body: {
email: "xxx",
password: "xxx"
}
}).then((resp) => {
window.localStorage.setItem('jwt', resp.body.token)
// console.log(resp.body.token)
cy.log(resp)
})
cy.visit('/')
这是赛普拉斯测试输出的图像:
Cypress test
这是 Chrome 控制台的图像,显示成功的响应代码:
Chrome console
阅读 Cypress command log 后,我注意到白色圆圈表示请求无法到达服务器(请求被存根)。发生这种情况的可能原因是什么?
提前致谢!
cy.intercept() cannot be debugged using cy.request()! Cypress only intercepts requests made by your front-end application.
这意味着您在测试中发出的任何 cy.request()
无法被拦截,因此无法被存根。
我会说白色圆圈表示响应来自浏览器缓存(只是猜测)。
更新
我已经设法解决了我的问题。该请求正在运行,但是我没有在本地存储中设置正确的数据以进行身份验证。使用Google Chrome Developer tools后,发现请求后auth._token.local和auth.refresh_token.local都需要设置。我附上了下面的代码片段,以帮助遇到类似问题的任何人。谢谢
cy.request({
method: 'POST',
url: 'http://127.0.0.1:8000/api/login',
body: {
email: "email",
password: "password",
}
}).then((resp) => {
localStorage.setItem('auth._token.local', 'Bearer ' + resp.body.token)
localStorage.setItem('auth._refresh_token.local', false)
});
cy.visit('/');
我正在使用 Cypress 为网站编写端到端测试,并想发出 API POST 请求来验证用户。
我已经能够发出一个请求,发送回一个带有适当 jwt 的 200 响应代码。
这是请求的代码片段:
Cypress.Commands.add('login', () => {
cy.request({
method: 'POST',
url: 'https://api.website.com/api/login',
body: {
email: "xxx",
password: "xxx"
}
}).then((resp) => {
window.localStorage.setItem('jwt', resp.body.token)
// console.log(resp.body.token)
cy.log(resp)
})
cy.visit('/')
这是赛普拉斯测试输出的图像: Cypress test
这是 Chrome 控制台的图像,显示成功的响应代码: Chrome console
阅读 Cypress command log 后,我注意到白色圆圈表示请求无法到达服务器(请求被存根)。发生这种情况的可能原因是什么?
提前致谢!
cy.intercept() cannot be debugged using cy.request()! Cypress only intercepts requests made by your front-end application.
这意味着您在测试中发出的任何 cy.request()
无法被拦截,因此无法被存根。
我会说白色圆圈表示响应来自浏览器缓存(只是猜测)。
更新
我已经设法解决了我的问题。该请求正在运行,但是我没有在本地存储中设置正确的数据以进行身份验证。使用Google Chrome Developer tools后,发现请求后auth._token.local和auth.refresh_token.local都需要设置。我附上了下面的代码片段,以帮助遇到类似问题的任何人。谢谢
cy.request({
method: 'POST',
url: 'http://127.0.0.1:8000/api/login',
body: {
email: "email",
password: "password",
}
}).then((resp) => {
localStorage.setItem('auth._token.local', 'Bearer ' + resp.body.token)
localStorage.setItem('auth._refresh_token.local', false)
});
cy.visit('/');