如何在Cypress的其他.js文件中获取cy.wrap存储的数据?
问题原因分析
你遇到的token is undefined问题,核心是两个问题:
- 错误的别名使用方式:直接把
'@token'拼接成字符串,Cypress不会自动解析这个字符串为别名对应的token值,这只是普通字符串,自然取不到实际token。 - 异步命令执行顺序问题:Cypress命令是异步执行的,
cy.get_token()还没完成token生成,后续的cy.api就已经执行了,导致token还未被赋值。
解决方案
下面提供三种可行修复方式,可根据需求选择:
方案1:让get_token直接返回token,通过.then接收
修改命令文件command.js:
const data = require('../fixtures/User_data.json') Cypress.Commands.add('get_token', () => { // 返回api请求的链式调用,让命令可被后续.then接收结果 return cy.api({ method: "POST", url: "https://api-stg.sample.com/login", body: { "mobile_number": "+91" + data.mobile, "password": "p@ssw0rd" } }) .then((response) => { const token = response.body.data.access_token.token cy.log("Bearer token: " + token ) return token; // 返回token供后续使用 }) })
修改测试spec文件:
create_mobilenum () { cy.get_token().then(token => { cy.api({ method: "POST", url: "https://api-stg.sample.com/mobile_numbers", headers: { 'Authorization': `Bearer ${token}` }, // ... 其他请求参数 }) }) }
方案2:使用别名并通过cy.get('@token')获取
如果坚持用别名,需确保在token生成后再获取它(command.js保持不变):
create_mobilenum () { cy.get_token() // 等待别名生成,通过cy.get获取token cy.get('@token').then(token => { cy.api({ method: "POST", url: "https://api-stg.sample.com/mobile_numbers", headers: { 'Authorization': `Bearer ${token}` }, // ... 其他请求参数 }) }) }
方案3:将token存入Cypress环境变量(全局可用)
若需在多个测试用例复用token,可存入环境变量:
修改命令文件command.js:
const data = require('../fixtures/User_data.json') Cypress.Commands.add('get_token', () => { cy.api({ method: "POST", url: "https://api-stg.sample.com/login", body: { "mobile_number": "+91" + data.mobile, "password": "p@ssw0rd" } }) .then((response) => { const token = response.body.data.access_token.token cy.log("Bearer token: " + token ) // 将token存入环境变量 Cypress.env('authToken', token); }) })
修改测试spec文件:
create_mobilenum () { cy.get_token().then(() => { cy.api({ method: "POST", url: "https://api-stg.sample.com/mobile_numbers", headers: { 'Authorization': `Bearer ${Cypress.env('authToken')}` }, // ... 其他请求参数 }) }) }
额外检查点
确认登录接口的返回结构是否符合预期,可在Cypress控制台查看response具体内容,确保response.body.data.access_token.token路径正确,避免因接口返回结构变化导致取不到token。
内容的提问来源于stack exchange,提问作者Jimmy
相关产品推荐
相关产品推荐

