let studentName: any = '';
    cy.get('app-screen').find('input[id="studentName"]').invoke('val').as('name')
    cy.get('@name').then((name) => {
      studentName = name;
      cy.log('Student Name: ' + studentName )
    })
    cy.log('Student Name: ' + studentName )上面的代码打印第一个log语句的学生名称。
然后块外的log语句在测试运行程序中为空。
对于为什么值studentName不在外部打印,有什么帮助吗?如何获得then块之外的值?
发布于 2022-02-12 02:24:37
所发生的情况是测试运行程序通过测试并将它找到的命令添加到Cypress命令队列中。
当它添加行cy.log('Student Name: ' + studentName )时,它会在命令队列开始运行之前,即当studentName = ''运行时,得到studentName的值,就像它是。
但是它只在队列到达该命令后才执行cy.log(),这给人的印象是studentName没有被更新。
您可以将studentName的读取推迟到稍后使用.then(),.then回调中的任何内容只有在前面的队列命令之后才会执行。
let studentName: any = '';
cy.get('app-screen').find('input[id="studentName"]').invoke('val').as('name')
cy.get('@name').then((name) => {
  studentName = name;
  cy.log('Student Name: ' + studentName )
})
// Now get the updated studentName
cy.then(() => {
  cy.log('Student Name: ' + studentName )  // adds this to the queue after 
                                           // all previous commands have run
})其他选项
如果student对象在许多测试中很重要,请考虑在beforeEach()中创建它,并使用测试的function()形式。
beforeEach(() => {
  cy.get('app-screen')
    .find('input[id="studentName"]')
    .invoke('val')
    .as('name')
})
it('tests the student', function() {  // NOTE function not arrow function
  
  expect(this.name).to.eq('Saran')    // access with "this" prefix
})
it('also tests the student', function() {  // NOTE function not arrow function
  
  cy.log("Student: ' + this.name)    // still has value
})Script1.js
cy.fixture('studentData.json').then(studentData => {
  cy.get('app-screen')
    .find('input[id="studentName"]')
    .invoke('val')
    .then(name => {
      studentData.name = name
      cy.writeFile('cypress/fixtures/studentData.json', studentData)
    })
})Script2.js
import studentData from 'cypress/fixtures/studentData.json'
// Don't use cy.fixture('studentData.json') here 
// because the fixture command caches the data
// so update will not always be seenhttps://stackoverflow.com/questions/71084293
复制相似问题