则存储在挡路中的值在挡路外打印或在柏木中使用时为空 [英] Value stored in then block is empty when printed or used outside the block in cypress

查看:21
本文介绍了则存储在挡路中的值在挡路外打印或在柏木中使用时为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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 )

上面的代码打印第一个日志语句的学生姓名。

THEN挡路外的日志语句在Test Runner中为空。

有什么帮助解释为什么值studentName没有打印在挡路之外?如何获取then挡路之外的值?

推荐答案

测试运行程序运行测试并将其找到的命令添加到Cypress Command Queue

添加行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 seen

这篇关于则存储在挡路中的值在挡路外打印或在柏木中使用时为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆