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

如何在Cucumber-JS中为Scenario Outline的Examples加载JSON文件数据?

在Cucumber-JS中从JSON文件加载Scenario Outline测试数据

实现步骤:

  1. 准备JSON数据文件
    在项目根目录创建data/data.json,按需求组织请求数据:
{
  "testCases": [
    {
      "request": {"username": "kminchelle","password": "0lelplR"},
      "refreshRequest": {"expiresInMins": 30 }
    },
    // 可添加多组测试用例
    {
      "request": {"username": "test_user","password": "test_pass"},
      "refreshRequest": {"expiresInMins": 60 }
    }
  ]
}
  1. 通过Before Hook加载全局测试数据
    在support/hooks.js中编写钩子,读取JSON文件并挂载到Cucumber的World对象,让所有步骤都能访问:
const fs = require('fs');
const path = require('path');

let testData;

Before(function () {
  const dataFilePath = path.resolve(__dirname, '../data/data.json');
  testData = JSON.parse(fs.readFileSync(dataFilePath, 'utf8'));
  this.testData = testData;
});
  1. 修改Feature文件,用索引关联测试数据
    调整Scenario Outline,用测试用例索引替代硬编码数据,让每条用例对应JSON中的一组数据:
Feature: Api test for Login user and get token
Scenario Outline: Auth login get token with test case <index>
Given 加载测试用例 <index>
When 发送POST请求到 /auth/login
Then 响应状态码为200
Then 响应包含字符串类型的token
When 发送GET请求到 /auth/me 获取当前用户
Then 当前用户响应状态码为200
Then 验证当前用户响应数据
Given 加载测试用例 <index>
When 发送POST请求到 /auth/refresh 刷新会话
Then 刷新会话响应状态码为200
Then 验证刷新会话响应包含token数据

Examples: 
  | index |
  | 0     |
  | 1     |
  1. 更新Step定义,使用加载的测试数据
    在步骤文件中,通过索引获取对应测试用例,在请求中直接引用数据:
// 加载指定索引的测试用例
Given('加载测试用例 {int}', function (index) {
  this.currentCase = this.testData.testCases[index];
});

// 发送登录请求
When('发送POST请求到 /auth/login', async function () {
  this.loginResponse = await this.request.post('/auth/login').send(this.currentCase.request);
});

// 发送刷新会话请求
When('发送POST请求到 /auth/refresh 刷新会话', async function () {
  this.refreshResponse = await this.request.post('/auth/refresh').send(this.currentCase.refreshRequest);
});

补充说明:

  • 若仅需单组测试数据,可直接在步骤中使用this.testData.testCases[0],无需Scenario Outline的Examples参数。
  • 用索引关联的方式能让每条测试用例在Cucumber报告中单独展示,便于定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:03:42