我在 Cypress 中编写测试代码。UI登录已经测试没有问题,但是为了测试网站的其他部分,我想以编程方式登录以进行快速测试。该网站是用 PHP 编写的,并在标头的 set-cookie 中使用 laravel 会话,下面是我的代码:
规格
it('strategy #2: parse token from response headers', function () {
// if we embed our csrf-token in response headers
// it makes it much easier for us to pluck it out
// without having to dig into the resulting HTML
cy.request('/auth/login')
.its('headers')
.then((headers) => {
const laravel_session = headers['laravel_session']
cy.loginByCSRF(laravel_session)
.then((resp: any) => {
expect(resp.status).to.eq(200)
expect(resp.body).to.include('<span class="menu-item">Dashboard</span>')
})
})
// Set viewport to 1366px x 1024px
cy.viewport(1366, 1024)
命令.ts
Cypress.Commands.add('loginByCSRF', (laravel_session: string) => {
const username = environment.Admin_username
const password = environment.Admin_password
cy.request({
method: 'POST',
url: '/auth/login',
failOnStatusCode: false, // dont fail so we can make assertions
form: true, // we are submitting a regular form body
body: {
username,
password,
_laravel_session: laravel_session, // insert this as part of form body
},
})
})
索引.d.ts
declare namespace Cypress {
interface Chainable {
loginByCSRF: typeof loginByCSRF
}
}
function loginByCSRF(laravel_session) {
return this.headers
}
任何帮助表示赞赏。谢谢!