jest测试react项目引入scss报错问题 解决

报错内容如下,经过各种排查后,发现是配置问题导致的错误。因为一开始初始化 jest.config.js并没有配置这一项。

FAIL  app/tests/HomePage.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    D:\资料\study\react学习\webpack5+react17项目搭建学习\demo案例\BI-portal-frontend\app\components\HomePage\HomePage.scss:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.home {
                                                                                             ^

    SyntaxError: Unexpected token '.'

      3 | import { bindActionCreators } from 'redux'
      4 | import { getProudectList } from '../../actions/data'
    > 5 | import styles from './HomePage.scss'
        | ^
      6 | 
      7 | 
      8 | class HomePage extends React.Component{

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at Object.<anonymous> (app/components/HomePage/HomePage.jsx:5:1)

image.png

解决方案:

1,npm install --dev identity-obj-proxy

2,在jest.config.js文件中配置如下属性。
image.png
 moduleNameMapper: {
    "\\.(css|scss)$": "identity-obj-proxy"
  },

3,重新执行测试命令 npm run test
image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容