首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当打印或在柏树块外使用时,存储在该块中的值为空。

当打印或在柏树块外使用时,存储在该块中的值为空。
EN

Stack Overflow用户
提问于 2022-02-11 17:36:57
回答 1查看 474关注 0票数 2
代码语言:javascript
运行
复制
    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块之外的值?

EN

回答 1

Stack Overflow用户

发布于 2022-02-12 02:24:37

所发生的情况是测试运行程序通过测试并将它找到的命令添加到Cypress命令队列中。

当它添加行cy.log('Student Name: ' + studentName )时,它会在命令队列开始运行之前,即当studentName = ''运行时,得到studentName的值,就像它是

但是它只在队列到达该命令后才执行cy.log(),这给人的印象是studentName没有被更新。

您可以将studentName的读取推迟到稍后使用.then(),.then回调中的任何内容只有在前面的队列命令之后才会执行。

代码语言:javascript
运行
复制
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()形式。

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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 seen
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71084293

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档