0

知道为什么在赛普拉斯测试运行期间删除了 localStorage 中设置的“令牌”吗?

我在 commands.js 文件中编写了“loadToken()”函数,在运行测试时我可以看到正在设置令牌,但是一旦cy.visit('/dashboard')被调用,令牌就会被删除/消失并且仍然显示登录页面并且不允许登录。同样的方式也适用于其他一些项目。注意:当我们实际点击 baseUrl [https://some-url.net] 时,它实际上将以下扩展名添加到 url '/auth/login'

Cypress.Commands.add('loadTokens', () => {
    return cy.fixture('tokenData.json').then(data => {
        const keys = Object.keys(data);
        keys.forEach(key => {
            window.localStorage.setItem(key, data[key]);
        });
    });
});

我在每个之前调用loadTokens()and loginRequest()inside;

context('Login and Logout test',() => {
  before(()=>{
  cy.visit('/');
})

beforeEach(() => {
  cy.loadTokens();
  cy.loginRequest();
})

it.only('Check whether the login is possible',() => {
    cy.viewport(1600, 1000); 
    cy.get('#offCanvasLeft > ul > li > a > span').eq(1).invoke('text').then((text)=>{
        expect(text).to.equal("Dashboard");
    }) 
})

})

Cypress.Commands.add('loginRequest', () => {
  const accessToken = localStorage.getItem('tokens');
    var cookieValue = document.cookie.split(';');
    cy.request({
      method: 'GET',
      url: baseUrl+`/dashboard`,
      headers: {
        'content-type': 'text/html',
        'tokens': `${accessToken}`,
        'cookie': `${cookieValue}`
      }
    })
  })

//cypress.json 文件:

{
  "baseUrl": "https://some-url.net",
  "numTestsKeptInMemory": 3,
  "chromeWebSecurity": false
}

//在 cypress 测试命中cy.visit()命令之前,我能够看到令牌集。 在此处输入图像描述

4

1 回答 1

0

这个Cypess 示例配方显示了在本地存储和 cy.visit() 中使用令牌的模式略有不同。

// 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
})

我认为onBeforeLoad()回调用于解决您在 cy.visit() 清除本地存储时遇到的问题。

所以,你的代码会是这样的

beforeEach(function setTokensAndVisit () {
  cy.fixture('tokenData.json').then(tokenData => {
    cy.visit('/dashboard', {
      onBeforeLoad (win) {

        // Set cookie or load localStorage with tokenData here,
        // depending on how your app checks that user is authorized.

        // In a SPA app, this check is likely to done in the router

      },
    })
  })
})
于 2020-03-28T04:53:18.003 回答