常规登录
// 直接提交表单,凭证入cookie中,登录成功
it('redirects to /dashboard on success', function () {
cy.get('input[name=username]').type(username)
cy.get('input[name=password]').type(password)
cy.get('form').submit()
// we should be redirected to /dashboard
cy.url().should('include', '/dashboard')
cy.get('h1').should('contain', 'jane.lane')
// and our cookie should be set to 'cypress-session-cookie'
cy.getCookie('cypress-session-cookie').should('exist')
})
Cypress.Commands.add('login', (userType, options = {}) => {
const accountTypes = {
admin:{
"username":"xxx",
"password":"xxx",
}
}
cy.request({
url:'your URL address',
method:'POST',
body:accountTypes[userType]
})
})
CSRF Tokens
// 自定义命令发请求,但还有csrf隐藏域
Cypress.Commands.add('loginByCSRF', (csrfToken) => {
cy.request({
method: 'POST',
url: '/login',
failOnStatusCode: false, // dont fail so we can make assertions
form: true, // we are submitting a regular form body
body: {
username,
password,
_csrf: csrfToken // insert this as part of form body
}
})
})
// csrf在返回的html中
it('strategy #1: parse token from HTML', function(){
// if we cannot change our server code to make it easier
// to parse out the CSRF token, we can simply use cy.request
// to fetch the login page, and then parse the HTML contents
// to find the CSRF token embedded in the page
cy.request('/login')
.its('body')
.then((body) => {
// we can use Cypress.$ to parse the string body
// thus enabling us to query into it easily
const $html = Cypress.$(body)
const csrf = $html.find("input[name=_csrf]").val()
cy.loginByCSRF(csrf)
.then((resp) => {
expect(resp.status).to.eq(200)
expect(resp.body).to.include("<h2>dashboard.html</h2>")
})
})
...
})
// 如果csrf在响应头中
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('/login')
.its('headers')
.then((headers) => {
const csrf = headers['x-csrf-token']
cy.loginByCSRF(csrf)
.then((resp) => {
expect(resp.status).to.eq(200)
expect(resp.body).to.include("<h2>dashboard.html</h2>")
})
})
...
})
设置COOKIE,实现登录
// 登录凭证不自动存入cookie,需手工操作
describe('Logging in when XHR is slow', function(){
const username = 'jane.lane'
const password = 'password123'
const sessionCookieName = 'cypress-session-cookie'
// the XHR endpoint /slow-login takes a couple of seconds
// we so don't want to login before each test
// instead we want to get the session cookie just ONCE before the tests
before(function () {
cy.request({
method: 'POST',
url: '/slow-login',
body: {
username,
password
}
})
// cy.getCookie automatically waits for the previous
// command cy.request to finish
// we ensure we have a valid cookie value and
// save it in the test context object "this.sessionCookie"
// that's why we use "function () { ... }" callback form
cy.getCookie(sessionCookieName)
.should('exist')
.its('value')
.should('be.a', 'string')
.as('sessionCookie')
})
beforeEach(function () {
// before each test we just set the cookie value
// making the login instant. Since we want to access
// the test context "this.sessionCookie" property
// we need to use "function () { ... }" callback form
cy.setCookie(sessionCookieName, this.sessionCookie)
})
it('loads the dashboard as an authenticated user', function(){
cy.visit('/dashboard')
cy.contains('h1', 'jane.lane')
})
it('loads the admin view as an authenticated user', function(){
cy.visit('/admin')
cy.contains('h1', 'Admin')
})
})
通过API登录
// login just once using API
let user
before(function fetchUser () {
cy.request('POST', 'http://localhost:4000/users/authenticate', {
username: Cypress.env('username'),
password: Cypress.env('password'),
})
.its('body')
.then((res) => {
user = res
})
})
// but set the user before visiting the page
// so the app thinks it is already authenticated
beforeEach(function setUser () {
cy.visit('/', {
onBeforeLoad (win) {
// and before the page finishes loading
// set the user object in local storage
win.localStorage.setItem('user', JSON.stringify(user))
},
})
// the page should be opened and the user should be logged in
})
...
/ use token
it('makes authenticated request', () => {
// we can make authenticated request ourselves
// since we know the token
cy.request({
url: 'http://localhost:4000/users',
auth: {
bearer: user.token,
},
})
.its('body')
.should('deep.equal', [
{
id: 1,
username: 'test',
firstName: 'Test',
lastName: 'User',
},
])
})
官方资料