让Jest返回正确的图像路径(typescript + react)



我正在编写一个React应用程序,我以以下方式导入图像:

import image1Src from 'assets/img1.png";

在我的测试中,我想在<img/>src路径上做断言,因此我需要在运行Jest测试时导入工作。我已经找到了很多返回硬编码字符串的解决方案,这是不够的,因为我需要实际测试src路径。

我找到的最接近的东西是:

import path from 'path';
// https://github.com/facebook/jest/issues/2838
module.exports = {
process: (_: unknown, filename: string): string => {
return `module.exports = '${JSON.stringify(path.basename(filename))}';`;
},
};

但是它不起作用,它返回函数{ process: [Function: process] }

任何想法?

您应该使用转换配置。

注意:除非文件发生更改,否则转换器只对每个文件运行一次。在转换器的开发过程中,使用——no-cache来运行Jest以频繁地删除Jest的缓存是很有用的。

jest.config.js:

module.exports = {
preset: 'ts-jest/presets/js-with-ts',
transform: {
'\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/examples/68838761/fileTransformer.js',
},
};

fileTransformer.js:

const path = require('path');
module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(filename) + ';';
},
};

index.test.ts:

//@ts-ignore
import image1Src from './assets/img1.png';
describe('68838761', () => {
test('should pass', () => {
console.log(image1Src);
});
});

命令:

jest -o --no-cache

在测试文件中导入assets/img1.png文件时,您将获得绝对文件路径。测试结果:

PASS  examples/68838761/index.test.ts (9.171 s)
68838761
✓ should pass (13 ms)
console.log
/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/examples/68838761/assets/img1.png
at Object.<anonymous> (examples/68838761/index.test.ts:6:13)
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.229 s

最新更新