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

使用Jest测试Electron+TypeScript应用时遇require图片语法错误

解决Jest测试Electron应用时require图片报错的问题

问题本质

Jest默认只处理JS/TS文件,当代码里用require引入.png这类静态资源时,Jest不知道如何解析,就会抛出SyntaxError: Invalid or unexpected token错误。而Electron运行时或打包工具(如Webpack)会自动处理这类资源路径,所以正常运行没问题,但测试时需要额外配置。

方案一:使用jest-transform-stub快速处理

  1. 安装依赖
npm install jest-transform-stub --save-dev
  1. 修改jest.config.ts,更新转换规则并添加文件扩展名支持:
import type { Config } from '@jest/types';

export default async (): Promise<Config.InitialOptions> => ({
    preset: 'ts-jest',
    testMatch: ['**.test.ts'],
    rootDir: '../',
    transform: {
        '^.+\\.(ts)$': 'ts-jest',
        // 新增:用jest-transform-stub处理静态资源
        '^.+\\.(png|jpg|jpeg|gif|svg)$': 'jest-transform-stub'
    },
    // 新增:告诉Jest这些扩展名的文件是合法模块
    moduleFileExtensions: ['ts', 'js', 'png', 'jpg']
});
  1. 给TS添加图片模块声明(避免TS编译报错):在src目录下创建declarations.d.ts文件,内容如下:
declare module '*.png' {
    const value: string;
    export default value;
}
declare module '*.jpg' {
    const value: string;
    export default value;
}
// 其他需要的图片格式可同理添加

方案二:手动配置Mock(无需额外安装包)

如果不想新增依赖,可以手动给静态资源做Mock:

  1. 在项目根目录创建__mocks__/fileMock.ts文件,内容:
export default 'test-static-resource-path';
  1. 修改jest.config.ts,添加资源映射规则:
import type { Config } from '@jest/types';

export default async (): Promise<Config.InitialOptions> => ({
    preset: 'ts-jest',
    testMatch: ['**.test.ts'],
    rootDir: '../',
    transform: {
        '^.+\\.(ts)$': 'ts-jest'
    },
    // 新增:把所有图片资源映射到Mock文件
    moduleNameMapper: {
        '\\.(png|jpg|jpeg|gif|svg)$': '<rootDir>/__mocks__/fileMock.ts'
    }
});
  1. 同样需要添加TS模块声明(和方案一的declarations.d.ts内容一致)。

验证

修改完配置后,重新运行测试命令:

npm run test

此时测试应该能正常执行,同时应用里的图片引用也不会受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:53:24