在E2E测试中,如何验证loader与action的正确执行?请说明Cypress或Playwright方案。

解读

该问题考察候选人对React Router v7新特性的理解,以及在E2E测试场景中如何验证动态数据加载与导航操作的执行逻辑。需要结合实际开发中常见的测试需求,如数据一致性、异步行为、错误处理等,说明具体的测试方法和实现细节。同时,需体现对Cypress或Playwright工具链的掌握,包括如何模拟用户交互、拦截网络请求、断言响应数据等。

知识点

  1. React Router v7的loader与action机制

    • loader用于在路由加载时获取数据(如通过loader函数返回Promise)
    • action用于在导航时执行数据修改(如通过action函数返回Promise)
    • 两者均与React组件解耦,通过路由配置定义
  2. E2E测试的核心目标

    • 验证用户交互流程的正确性
    • 确保数据加载与导航逻辑的可靠性
    • 检查错误边界与异常处理机制
  3. Cypress/Playwright测试工具特性

    • Cypress:内置网络请求拦截(cy.intercept)、断言(cy.get)、时间控制(cy.wait)
    • Playwright:支持路由拦截(page.route)、异步等待(page.waitFor)、断言(page.locator)

答案

验证loader与action的执行需通过以下步骤实现:

1. 模拟路由导航触发

使用cy.visit或page.goto访问目标路由,确保导航事件被触发。例如:

// Cypress  
cy.visit('/user/123');  
// Playwright  
await page.goto('/user/123');  

2. 拦截网络请求验证loader

通过拦截loader发起的网络请求,检查响应数据是否符合预期:

// Cypress  
cy.intercept('GET', '/api/user/123').as('userRequest');  
cy.visit('/user/123');  
cy.wait('@userRequest')  
  .its('response.body')  
  .should('deep.equal', { id: 123, name: '张三' });  

// Playwright  
await page.route('/api/user/123', async (route) => {  
  await route.fulfill({  
    status: 200,  
    body: { id: 123, name: '张三' }  
  });  
});  
await page.goto('/user/123');  
await expect(page.locator('#user-name')).toHaveText('张三');  

3. 验证action的执行逻辑

通过监听路由导航事件,检查action是否正确修改数据:

// Cypress  
cy.intercept('POST', '/api/user/update').as('updateRequest');  
cy.get('#update-button').click();  
cy.wait('@updateRequest')  
  .its('response.body')  
  .should('deep.equal', { success: true, id: 123 });  

// Playwright  
await page.route('POST', '/api/user/update', async (route) => {  
  const request = await route.request();  
  const response = await fetch('/api/user/update', {  
    method: 'POST',  
    body: JSON.stringify({ id: 123, name: '李四' })  
  });  
  await route.fulfill({  
    status: 200,  
    body: await response.json()  
  });  
});  
await page.click('#update-button');  
await expect(page.locator('#user-name')).toHaveText('李四');  

4. 检查错误边界与异常处理

通过故意触发错误(如模拟失败的loader请求),验证错误边界是否正确捕获并渲染:

// Cypress  
cy.intercept('GET', '/api/user/123', { statusCode: 500 }).as('errorRequest');  
cy.visit('/user/123');  
cy.get('#error-message').should('contain.text', '加载失败');  

// Playwright  
await page.route('GET', '/api/user/123', async (route) => {  
  await route.fulfill({  
    status: 500,  
    body: 'Internal Server Error'  
  });  
});  
await page.goto('/user/123');  
await expect(page.locator('#error-message')).toHaveText('Internal Server Error');  

拓展思考

  • 结合React 18/19特性:在使用并发模式时,需通过cy.wait或page.waitFor确保异步操作完成后再进行断言,避免因渲染延迟导致的测试误判。
  • 代码分割验证:通过监控加载时间(如cy.clock)和资源加载状态(如cy.get('script[src*="chunk"]')),验证代码分割是否按预期加载。
  • 性能优化:在测试中加入cy.performance或page.metrics,量化loader/action执行的耗时,确保符合预加载策略的优化目标。
  • 测试稳定性:通过封装测试逻辑为可复用的模块(如cy.stub或page.route),减少因环境差异导致的测试不稳定问题。