如何使用Jest测试DateService类的getDaysInMonth方法?
如何用Jest测试DateService的getDaysInMonth方法
你可以创建对应的测试文件(比如date.service.test.ts),编写以下测试用例覆盖不同场景:
import { DateService } from './date.service'; import { getDaysInMonth } from 'date-fns'; // 可选:Mock date-fns的getDaysInMonth函数,验证调用逻辑 jest.mock('date-fns', () => ({ ...jest.requireActual('date-fns'), getDaysInMonth: jest.fn(), })); describe('DateService', () => { let dateService: DateService; beforeEach(() => { dateService = new DateService(); (getDaysInMonth as jest.Mock).mockClear(); }); test('不传参数时,调用date-fns的getDaysInMonth并传入当前日期', () => { dateService.getDaysInMonth(); expect(getDaysInMonth).toHaveBeenCalledWith(expect.any(Date)); }); test('传入指定日期时,返回对应月份的正确天数', () => { // 闰年2月(2024年) const leapFeb = new Date(2024, 1, 5); expect(dateService.getDaysInMonth(leapFeb)).toBe(29); // 非闰年2月(2023年) const nonLeapFeb = new Date(2023, 1, 10); expect(dateService.getDaysInMonth(nonLeapFeb)).toBe(28); // 31天的月份(比如1月) const january = new Date(2024, 0, 1); expect(dateService.getDaysInMonth(january)).toBe(31); // 30天的月份(比如4月) const april = new Date(2024, 3, 15); expect(dateService.getDaysInMonth(april)).toBe(30); }); });
如果不需要验证函数调用,仅需断言结果,可去掉mock部分,直接测试返回值即可。
如何访问getDaysInMonth的实现逻辑
你的DateService.getDaysInMonth只是对date-fns同名函数的一层封装,核心逻辑在date-fns库中,可通过以下方式查看实现:
- IDE直接跳转:在VSCode等支持代码导航的编辑器中,按住Ctrl(Windows/Linux)或Cmd(Mac)键,点击代码里的
getDaysInMonth调用,直接跳转到date-fns库中该函数的源码文件。 - 查看本地依赖源码:打开项目的
node_modules/date-fns目录,找到src/getDaysInMonth/index.js文件,直接阅读其中的实现代码。 - 查看类型声明:若需了解函数的参数、返回值类型,可查看
node_modules/date-fns/types/index.d.ts中的对应类型定义。
内容的提问来源于stack exchange,提问作者der papa
相关产品推荐
相关产品推荐

