简体   繁体   English

如何在 Gatsby 3 中为 CSS 模块设置 Jest?

[英]How to set up Jest for CSS modules in Gatsby 3?

In Gatsby 3 import styles from './styles.module.css' syntax is no longer supported and has been replaced with import * as styles from './styles.module.css' .在 Gatsby 3 中,不再支持import styles from './styles.module.css'语法,并已替换为import * as styles from './styles.module.css'

Unfortunately, using the new syntax doesn't work with the suggested Jest setup, ie using identity-obj-proxy for CSS modules - accessing any property on styles object returns undefined rather than the property name.不幸的是,使用新语法不适用于建议的 Jest 设置,即对 CSS 模块使用identity-obj-proxy - 访问styles object 上的任何属性返回undefined而不是属性名称。

It does work correctly when I'm using named imports, eg import { wrapper } from './styles.module.css' , but as I'm migrating a rather large app to Gatsby 3, I'd prefer to initially use import * as styles... syntax.当我使用命名导入时它确实工作正常,例如import { wrapper } from './styles.module.css' ,但是当我将一个相当大的应用程序迁移到 Gatsby 3 时,我更愿意最初使用import * as styles...语法。

Is there any other recommended way to set up Jest that would work with both import * as styles from... and import { wrapper} from... ?是否有任何其他推荐的方法来设置 Jest 可以与import * as styles from...import { wrapper} from...一起使用?

There's a solution provided in one of the open issues for identity-object-proxy . identity-object-proxy的一个开放问题中提供了一个解决方案 It allows you to use import * as styles... syntax to satisfy Gatsby by modifying Jest's configuration.它允许您使用import * as styles...语法通过修改 Jest 的配置来满足 Gatsby。

Create a mock to modify identity-object-proxy for style files:创建一个模拟来修改样式文件identity-object-proxy

// .jest/__mocks__/identity-object-proxy-esm.js

module.exports = new Proxy(
  {},
  {
    get: function getter(target, key) {
      if (key === '__esModule') {
        // True instead of false to pretend we're an ES module.
        return true;
      }
      return key;
    }
  }
);

And update jest config to use the mock:并更新 jest 配置以使用模拟:

// jest.config.js 

module.exports = {
  ...
  moduleNameMapper: {
    '\\.(jpg|jpeg|png|gif|webp|svg)$': 'identity-obj-proxy',
    '\\.(css|scss)$': '<rootDir>/.jest/__mocks__/identity-obj-proxy-esm.js'
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM