Angular服务测试时出现__WEBPACK_IMPORTED_MODULE_2_moment__.tz不是函数错误
解决Angular 2单元测试中
moment.tz is not a function的问题 这个问题的核心原因很明确:moment-timezone是moment的插件,需要正确挂载到moment实例上才能生效,普通moment的导入并不会自动带上时区扩展功能。下面是一步步的解决方案:
1. 先确认依赖安装完整
确保你的项目中同时安装了moment和moment-timezone,版本要兼容:
npm install moment moment-timezone --save-dev
2. 调整测试文件的导入顺序
moment-timezone需要在moment之后导入,这样它才能把tz方法注入到moment的原型链中。修改你的单元测试文件:
import { TestBed } from '@angular/core/testing'; import { YourTargetService } from './your-target.service'; // 第一步:导入基础moment import * as moment from 'moment'; // 第二步:导入时区扩展,自动挂载tz方法 import 'moment-timezone'; describe('YourTargetService', () => { let service: YourTargetService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(YourTargetService); }); it('should use moment.tz correctly', () => { // 现在可以正常调用tz方法了 const nyTime = moment.tz('2024-05-20 12:00', 'America/New_York'); expect(nyTime.format()).toBe('2024-05-20T12:00:00-04:00'); }); });
3. 匹配服务中的导入方式
如果你的服务代码中是直接导入moment-timezone作为moment使用(比如下面这样):
// 服务中的代码 import moment from 'moment-timezone'; @Injectable() export class YourTargetService { getTimeInLondon(dateStr: string) { return moment.tz(dateStr, 'Europe/London').format(); } }
那测试文件中也要保持一致的导入方式,不要分开导入moment和moment-timezone:
// 测试文件对应修改 import moment from 'moment-timezone';
4. 排查潜在的覆盖问题
检查测试文件中有没有其他地方重新赋值了moment变量,比如:
// 错误示例:这样会覆盖带tz扩展的moment实例 const moment = jest.fn();
如果有这类代码,会导致原本的moment实例被替换,自然找不到tz方法。
内容的提问来源于stack exchange,提问作者codeepic
相关产品推荐
相关产品推荐

