Cypress beforeEach钩子POST请求报错跳过剩余测试用例解决方案求助
错误原因
- 第一,语法层级错误:
it测试用例块被错误写在beforeEach钩子内部,属于Cypress语法的严重错误,会直接导致钩子执行逻辑混乱触发报错。 - 第二,异步变量作用域错误:原代码中
it块内的data变量仅在cy.fixture的then回调作用域内有效,回调外直接调用data.url/data.token会读取到undefined,导致请求参数错误触发报错。 - 第三,可选优化点:可抽提公共fixture读取逻辑,避免每个用例重复读取配置文件。
修正后完整代码
// 外层用describe包裹测试套件 describe("拍卖列表接口测试", () => { // 公共配置变量,存储fixture读取结果 let testConfig; // 测试套件初始化时仅读取一次配置文件 before(() => { cy.fixture("token.json").then(data => { testConfig = data; }) }) // 每个测试用例前执行初始化接口,和it块平级 beforeEach(() => { cy.request({ method: "POST", url: testConfig.url + "/setup", headers: { Authorization: testConfig.token, "content-type": "application/json", }, body: { "test-case": "base", }, failOnStatusCode: false, }).then((res) => { expect(res.status).to.eq(200); }); }); // 测试用例写在describe内部、与beforeEach平级 it("get a list of auctions filtered by the options passed in the body", () => { cy.request({ method: "POST", url: testConfig.url, headers: { Authorization: testConfig.token, "content-type": "application/json", }, body: { auctionType: ["basic_auction"], statuses: ["ongoing"], }, failOnStatusCode: false, }).then((res) => { expect(res.status).to.eq(200); // 断言逻辑 assert.isNotNull(res.body, "响应体不为空"); assert.isNotNull(res.body.createdAt, "createdAt字段不为空"); }); }); })
内容的提问来源于stack exchange,提问作者Luna
相关产品推荐
相关产品推荐

