基于 ES6 Proxy 的身份对象:模拟 CSS 模块导入

identity-obj-proxy 利用 ES6 代理创建身份对象,用于模拟 webpack 导入,例如 CSS 模块。当测试框架(如 Jest)需要处理 CSS 模块导入时,identity-obj-proxy 可模拟该行为。

使用方法

假设有以下 React 组件:

import React, { Component } from 'react';
import styles from './App.css'; // 使用 CSS Modules

export default class App extends Component {
  render() {
    return (
      

Hello World

); } }

在测试环境中,可以使用 identity-obj-proxy 模拟 styles 对象,确保 styles.container 返回预期的类名:

// 测试代码示例
import proxy from 'identity-obj-proxy';

jest.mock('./App.css', () => proxy, { virtual: true });

通过这种方式,styles.container 将返回 'container',而无需实际加载 CSS 文件。

优势

  • 简化 CSS 模块的测试配置。
  • 提高测试效率,无需加载实际的 CSS 文件。
zip 文件大小:9.33KB