You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS及Cypress跨文件引入dataStore.js取值为undefined问题咨询

问题说明
  • 原生JS场景:创建dataStore.js作为全局数据存储对象,按指定逻辑向对象写入字符串值后,在Home.js中通过console.log读取打印值时得到undefined,咨询问题原因
  • Cypress v10.2.0自动化测试场景:将相同实现逻辑应用于测试框架时,同一测试文件内的不同测试用例可正常读取已存储的值,但跨测试文件读取dataStore中存储的globaldata字段时返回undefined,需要问题定位建议
相关实现代码

1. 原生JS场景

dataStore.js

let dataStore = {
    globaldata1: {},
    globaldata2: {}
}

export { dataStore }

profile.js

let datastore = require("../global/dataStore");

let myStr1 = "This is a string" ;
let myStr2 = "This is another string" ;
datastore.globaldata1 = myStr1;
datastore.globaldata2 = myStr2;

home.js

let datastore = require("../global/dataStore");

let globalStr1 = datastore.globaldata1 ;
console.log("Print the data::"+globalStr1);

let globalStr2 = datastore.globaldata2  ;
console.log("Print the second data::"+globalStr2);

2. Cypress v10.2.0测试场景

dataStore.js

let dataStore = {
    globaldata: {}
}

export { dataStore }

site.Cy.js

let dataStore = require("../../../support/dataStore");
import "cypress-localstorage-commands";

describe('Verify the Global data saving', () => {

  context('Global data', () => {
    beforeEach(() => {
      cy.restoreLocalStorage();
      cy.visit('/');
    });

   
    it('First get the text and Save globally', () => {
 
      cy.get('#companyNameDiv > span').invoke('text').then((text)=>{
         dataStore.globaldata = text;
         console.log("First test outcome:: " +dataStore.globaldata); // 此处打印正常
      });
    });

    it('Use that text in second test', () => {
      console.log("Yeh, global text in second test :: " +dataStore.globaldata );  // 此处打印正常
    });
  });
});

another.Cy.js

let dataStore = require("../../../support/dataStore");
import "cypress-localstorage-commands";

describe('Retrive another test file', () => {
  context('Retrive saved data in another test file', () => {

    it('Get the text', () => {
     console.log("Yeh, another test file:: " +dataStore.globaldata); 
     // 此处取值返回undefined
    });
  });
});

内容的提问来源于stack exchange,提问作者soccerway

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 06:51:21