导入图像打破了笑话测试 [英] Importing images breaks jest test

查看:22
本文介绍了导入图像打破了笑话测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 React 组件中导入资产(例如,从../../../assets/img/logo.png"导入徽标)给出这样的错误

In React components importing assets (ex, import logo from "../../../assets/img/logo.png) gives such error

({"Object.":function(module,exports,require,__dirname,__filename,global,jest){ PNG
语法错误:无效或意外的令牌在 ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)

({"Object.":function(module,exports,require,__dirname,__filename,global,jest){�PNG
SyntaxError: Invalid or unexpected token at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)

我的笑话配置是

"jest": {
"testRegex": ".*\.spec\.js$",
"moduleFileExtensions": [
  "js",
  "jsx",
  "json"
],
"moduleDirectories": [
  "node_modules",
  "src",
  "assets"
],
"moduleNameMapper": {
  "\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$/": "<rootDir>/__mocks__/fileMock.js",
  "\.(css|less|scss)$": "<rootDir>/__mocks__/styleMock.js"
},
"verbose": true,
"bail": true
}

我错过了什么?

推荐答案

当您导入图像文件时,Jest 尝试将图像的二进制代码解释为 .js,因此遇到错误.

When you import image files, Jest tries to interpret the binary codes of the images as .js, hence runs into errors.

唯一的出路是在 jest 看到图像导入时模拟默认响应!

The only way out is to mock a default response anytime jest sees an image import!

  • 首先你告诉 Jest 在每次遇到图像导入时运行模拟文件.您可以通过将下面的密钥添加到您的 package.json 文件中来做到这一点
"jest": {
 "moduleNameMapper": {
      "\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
      "\.(css|less)$": "<rootDir>/__mocks__/fileMock.js"
    }
}

注意:如果您已经有了 Jest" 键,只需在其中添加 moduleNameMapper" 子项

Note: if you already have the "Jest" key, just add the "moduleNameMapper" child in it

  • 最后,在您的根目录中创建一个 mocks 文件夹,并在其中创建 fileMock.js 文件.使用下面的代码段填充文件
  • lastly, create a mocks folder in your root and create fileMock.js file inside it. populate the file with the snippet below
module.exports = ''; 

注意:如果您使用的是 es6,您可以使用 export default ''; 来避免 Eslint 标志

Note: If you are using es6 you can use export default ''; to avoid an Eslint flag

完成上述步骤后,您可以重新开始测试,一切顺利.

when you are done with the above steps, you can restart the test and you are good to go.

注意.请记住在 moduleNameMapper 中添加图像文件的不同扩展名,以便它们可以被模拟.

Note. remember to add the varying extensions of your image files in the moduleNameMapper so that they can be mocked.

希望能帮到你.#干杯!

I hope I have been able to help. #cheers!

这篇关于导入图像打破了笑话测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆