Pactumjs+Cucumber技术问题:如何在步骤间存储复用Bearer Token
在Cucumber测试步骤中复用PactumJS的登录Token
方法一:使用Pactum的全局存储(stores)
Pactum内置全局存储机制,可直接在请求链中存储响应字段,后续步骤直接调用即可。
修改登录步骤,添加.stores()方法存储token:
Given('I call the login service', async () => { await pactum.spec() .post('/api/rest/login') .withHeaders('Content-Type', 'application/json') .withBody({ file: "json/login.json" }) .expectStatus(200) .stores('authToken', 'res.body.token') // 将响应中的token存储到全局键authToken .expect(ctx => { chai.expect(ctx.res.body.token).is.not.null; }); });
在后续接口调用步骤中,通过pactum.settings.get()获取存储的token:
When('I call the get points of sale service', async () => { const token = pactum.settings.get('authToken'); await pactum.spec() .get('/api/rest/admin') .withHeaders({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' }) .expectStatus(200); });
方法二:使用Cucumber的World上下文共享
如果不想用全局存储,可借助Cucumber的World上下文在步骤间传递数据,注意步骤必须使用function而非箭头函数才能访问this。
修改登录步骤,将token存入World:
Given('I call the login service', async function () { const token = await pactum.spec() .post('/api/rest/login') .withHeaders('Content-Type', 'application/json') .withBody({ file: "json/login.json" }) .expectStatus(200) .expect(ctx => { chai.expect(ctx.res.body.token).is.not.null; }) .returns('res.body.token'); // 返回指定的响应字段 this.authToken = token; // 将token存入Cucumber上下文 });
在后续步骤中从上下文读取token:
When('I call the get points of sale service', async function () { await pactum.spec() .get('/api/rest/admin') .withHeaders({ 'Authorization': `Bearer ${this.authToken}`, 'Content-Type': 'application/json' }) .expectStatus(200); });
注意事项
- 若使用
stores无效果,先检查token的响应路径是否正确(比如是否是res.body.data.token而非res.body.token) - 全局存储适合单线程测试场景,多线程并发测试建议用Cucumber上下文避免数据冲突
- 使用Cucumber上下文时,步骤必须用
function定义,箭头函数无法访问this
内容的提问来源于stack exchange,提问作者Mark Half
相关产品推荐
相关产品推荐

