在Jest中如何测试jQuery选择器是否被正确调用?
解决方案
监听$.fn.init的方式依赖jQuery未对外暴露的内部实现逻辑,不同版本间存在兼容性差异,稳定性差,更推荐直接监听对外暴露的$函数本身实现需求。
1. 全局引入jQuery的场景($挂载在window上)
直接对全局$做spy即可:
test('muteVideos 选择器参数正确', () => { // 监听全局$函数 const $spy = jest.spyOn(window, '$'); // 保留之前对prop的监听 const propSpy = jest.spyOn($.fn, 'prop'); // 执行待测试的muteVideos方法 // 示例:如果方法在类中,先实例化再调用 // const instance = new YourClass(); // instance.muteVideos(); // 断言 expect($spy).toBeCalledWith('video'); expect(propSpy).toBeCalledWith('muted', true); // 执行清理,避免影响其他测试用例 $spy.mockRestore(); propSpy.mockRestore(); });
2. ES模块导入jQuery的场景(import $ from 'jquery')
直接mock整个jQuery模块即可:
// 测试文件顶部先mock jQuery模块 jest.mock('jquery'); import $ from 'jquery'; test('muteVideos 选择器参数正确', () => { // 执行待测试的muteVideos方法 // const instance = new YourClass(); // instance.muteVideos(); // 断言 expect($).toBeCalledWith('video'); expect($('video').prop).toBeCalledWith('muted', true); });
内容的提问来源于stack exchange,提问作者Kartik Watwani
相关产品推荐
相关产品推荐

