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

Cypress测试航班日期异常:返程日期点击无实际触发效果

Cypress测试中返程日期点击不生效的解决方案

问题描述

我正在学习使用Cypress工具编写测试用例,目标是获取航班的首个可用机票价格。测试逻辑为选择首个可用的出发日期,再随机选择一个返程日期。当前测试中出发日期可正常选中,但返程日期执行.click()操作后,日历仅显示选中状态却未实际触发点击动作。

测试代码如下:

describe('Derive an airplane ticket prices from the calendar', () => {
    it('Should be able to open the webpage', () => {
        // cy.intercept('POST', 'https://www.mczbf.com/12706/pageInfo', {
        //     statusCode: 200,
        //     body: '',
        //     headers: {
        //         'access-control-allow-origin': '*',
        //     },
        // }).as('stubCrossOriginScript');

        cy.visit('https://airmalta.com/en');
        // cy.wait('@stubCrossOriginScript');
        cy.get('#onetrust-accept-btn-handler').click()

        //Click on `Departing from` option box:
        cy.get('.route-selection-origin > .input-holder > .form-control').click()
        cy.get('.input-drop-container > :nth-child(6)').contains('Vienna International').click()

        //Click on `Flying to` option box:
        cy.get('.route-selection-destination > .input-holder > .form-control').click()
        cy.get('.input-drop-container > :nth-child(2)').contains('Malta International Airport').click()

        //Select Departure date:
        cy.get("input[placeholder='dd/mm'][name='DepartureDate1']").click()


        cy.get('.DayPicker-Body') // Select the parent element
            .find('.DayPicker-Day[aria-disabled="false"]') // Find the day elements with aria-disabled="false"
            .first() // Select the first available date
            .click(); // Click on the first available date

        //*** To do later: assertoon for selected Departure date//

        // //Select Return date:
        cy.get("input[placeholder='dd/mm'][name='DepartureDate2']").click()
        cy.get('.DayPicker-Body')
            .find('.DayPicker-Day[aria-disabled="false"]:not([aria-selected="true"])') // Find the available dates not selected
            .then($dates => {
                const randomIndex = Cypress._.random(0, $dates.length - 1); // Generate a random index
                cy.wrap($dates[randomIndex]).click(); // Click on the randomly selected date
            });

        //*** To do later: assertoon for selected Return date//

        cy.get("button[class='btn btn-primary btn-lg d-none d-md-block']").click()
})

解决方法

1. 确保返程日期晚于出发日期

原代码仅排除了已选中的日期,但未保证返程日期在出发日期之后,页面可能因选中无效日期(早于出发日)而不响应。可以先获取出发日期的时间戳,再筛选出符合条件的返程日期:

// 先存储出发日期的时间
let departureDate;
cy.get('.DayPicker-Body')
  .find('.DayPicker-Day[aria-disabled="false"]')
  .first()
  .invoke('attr', 'data-date') // 假设日期元素有data-date属性存储日期值,格式如"2024-05-20"
  .then(dateStr => {
    departureDate = new Date(dateStr);
  })
  .click();

// 选择返程日期时筛选晚于出发日的日期
cy.get("input[placeholder='dd/mm'][name='DepartureDate2']").click()
cy.get('.DayPicker-Body')
  .find('.DayPicker-Day[aria-disabled="false"]:not([aria-selected="true"])')
  .then($dates => {
    // 筛选出晚于出发日的日期
    const validDates = Array.from($dates).filter(dateEl => {
      const dateStr = dateEl.getAttribute('data-date');
      return new Date(dateStr) > departureDate;
    });
    if (validDates.length === 0) {
      throw new Error('没有可用的返程日期');
    }
    const randomIndex = Cypress._.random(0, validDates.length - 1);
    cy.wrap(validDates[randomIndex]).click();
  });

2. 使用原生点击事件替代Cypress模拟点击

有时Cypress的.click()可能无法触发页面的原生交互逻辑,改用.trigger('click')强制触发原生事件:

cy.wrap(validDates[randomIndex]).trigger('click', { force: true });

3. 等待日历完全渲染后再操作

点击返程日期输入框后,添加断言等待日历DOM加载完成,避免因元素未就绪导致点击失效:

cy.get("input[placeholder='dd/mm'][name='DepartureDate2']").click()
cy.get('.DayPicker-Body').should('be.visible') // 等待日历可见
cy.get('.DayPicker-Body')
  .find('.DayPicker-Day[aria-disabled="false"]:not([aria-selected="true"])')
  .then($dates => {
    // ... 后续逻辑
  });

4. 强制点击可交互元素

如果存在透明遮罩层或元素层级问题,可使用{ force: true }跳过元素可交互性检查,直接点击:

cy.wrap(validDates[randomIndex]).click({ force: true });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:20:36