导入图像破坏测试 [英] Importing images breaks jest test

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

问题描述

在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
SyntaxError:无效或意外的令牌 在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.

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"子项

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 = ''; 
      
      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天全站免登陆