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

React Native中如何对演出列表过滤函数进行单元测试?

解决方案

一、提取过滤函数

完全可以把重复的过滤逻辑抽成独立的纯函数,让组件和测试共用,彻底避免代码冗余。

  1. 创建工具文件(比如src/utils/gigFilters.ts),封装过滤逻辑:
import { format } from 'date-fns'; // 按你实际使用的日期库调整,比如moment

export const filterGigsByDate = (gigs: Array<any>, targetDate: Date) => {
  const formattedTargetDate = format(targetDate, 'do MMMM Y');
  return gigs.filter(gig => {
    const gigDate = new Date(gig.dateAndTime.seconds * 1000);
    const formattedGigDate = format(gigDate, 'do MMMM Y');
    return formattedGigDate === formattedTargetDate;
  });
};
  1. 在listByDay.tsx组件中导入并使用:
import { filterGigsByDate } from '../utils/gigFilters';

// 组件内逻辑
const currentDate = new Date(currentDateMs);
const gigsToday = filterGigsByDate(gigs, currentDate);
  1. 修改测试代码,直接复用该函数:
import { filterGigsByDate } from '../src/utils/gigFilters';

test('should filter gigs by date', () => {
  const gigs = [
    { dateAndTime: { seconds: 1609459200 } }, // 2021年9月1日
    { dateAndTime: { seconds: 1609545600 } }, // 2021年9月2日
    { dateAndTime: { seconds: 1609632000 } }, // 2021年9月3日
  ];

  const targetDate = new Date(2021, 8, 1); // 2021年9月1日
  const gigsToday = filterGigsByDate(gigs, targetDate);

  expect(gigsToday).toEqual([{ dateAndTime: { seconds: 1609459200 } }]);
});

注意:测试里要用toEqual而非toBe,因为toBe比较对象引用,toEqual会深度对比对象内容。

二、适合的测试库

  • Jest:Expo项目默认集成Jest,完全能覆盖纯函数的单元测试需求,语法简洁,支持断言、模拟等核心功能,专门用来测试你提取的这类纯逻辑代码。
  • React Testing Library:如果需要测试listByDay.tsx组件的渲染行为(比如是否正确展示当天演出),可以搭配这个库。它专注于模拟用户真实交互来验证组件功能,符合前端测试的最佳实践。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:50:29