zoukankan      html  css  js  c++  java
  • Cypress 系列之----04 登录的不同实现

    常规登录

    // 直接提交表单,凭证入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')
        })
    

    HTML Web Forms

    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',
        },
      ])
    })
    

    官方资料

  • 相关阅读:
    Linux下通过.desktop 文件创建桌面程序图标及文件编写方式(Desktop Entry文件概述)
    Ubuntu16.04进入挂起或休眠状态时按任何键都无法唤醒问题解决办法
    Ubuntu16.04+Gnome3 锁定屏幕快捷键无效解决办法
    A start job is running for Raise network interface(5min 13s )问题解决方法
    Ubuntu16.04 “有线未托管”有线网络不可用问题解决
    A start job is running for Network Manager wait online (29s / no limit) 等待30s解决办法
    Linux 串口终端调试工具minicom
    Linux 终端仿真程序Putty
    Oracle:在 debian9 上完美安装 oracle 10.2.0.5 x64
    从debian9、ubuntu18.04的deb包依赖来看,似乎不是那么好!!
  • 原文地址:https://www.cnblogs.com/liuyitan/p/12594440.html
Copyright © 2011-2022 走看看