赛普拉斯-存储一个值以备后用

时间:2019-12-18 23:20:44

标签: javascript testing cypress

我有一个测试,我需要在其中获取链接的href,并将其存储到以后的测试中以供访问。

如果我编写两个不同的测试,它会很好:一个用于获取href,另一个用于访问href。但是,如果我在同一个测试中都完成了操作,那是行不通的,为什么?

// commands.js
Cypress.Commands.add('getInvitationLink', () => {
  cy.get('a.invitation-link')
    .should('have.attr', 'href')
    .then((href) => {
      assert.isOk(href, 'invitation is found')
      return cy.wrap(href)
    })
})

// invitation.spec.js - working

let invitationLink

it('get the invitation link', () => {
  cy.visit('/')

  cy.getInvitationLink().then(href => {
    invitationLink = href
  })

  // assert other stuff on the page...
})

it('access the invitation link', () => {
  cy.visit(invitationLink) // it works!
})
// invitation.spec.js - not working

let invitationLink

it('get the invitation link and access it', () => {
  cy.visit('/')


  cy.getInvitationLink().then(href => {
    invitationLink = href
  })

  // assert other stuff on the page...

  cy.visit(invitationLink) // it doesn't work! invitationLink is undefined

})

2 个答案:

答案 0 :(得分:0)

invitationLink是在promise的上下文中定义的。尝试在cy.visit内移动.then命令:

// invitation.spec.js - not working

let invitationLink;

it('get the invitation link and access it', () => {
  cy.visit('/');


  cy.getInvitationLink().then(href => {
    invitationLink = href;
    cy.visit(invitationLink);
    // assert other stuff on the page...

  });
});

答案 1 :(得分:0)

如果只是存储和使用值,则创建一个像这样的属性

const asyncLocalStorage = {
    setItem: async function (key, value) {

        return localStorage.setItem(key, value);
    },
    getItem: async function (key) {

        return localStorage.getItem(key);
    }
};

然后将值设置为

asyncLocalStorage.setItem('storedName', name)

并将值获取为

asyncLocalStorage.getItem('storedName').then((storedName) => {})

或者只是

  const name = asyncLocalStorage.getItem('storedName')