如何在 Jest 中使用单个导出索引文件处理 JS 库的对等依赖关系?

问题描述 投票:0回答:1

对蜿蜒的问题标题表示歉意,乍一看可能没有意义。让我解释一下。

我有一个名为

foo-bar-ui
的库包,用于一些共享 UI 组件。所有组件均从单个索引文件导出。

// index.js
export * from './lib/ComponentA';
export * from './lib/ComponentB';
export * from './lib/ComponentC';

在应用程序包中,我可以愉快地以以下格式从该库导入内容。

import { ComponentA, ComponentB } from 'foo-bar-ui';

有一天,我为

react-xyz
添加了一个新的第三方依赖项
ComponentC
。它仅由
ComponentC
使用,因此我将其声明为库包中的对等依赖项。如果需要使用
react-xyz
,任何使用此库的客户端应用程序都可以自行安装
ComponentC

但是,我当前的应用程序仅消耗

ComponentA
ComponentB
。 Webpack 捆绑完全没有任何抱怨,因为它会进行树摇动,从而完全丢弃
ComponentC
,因此没有关于丢失
react-xyz
的警告。但 Jest 对此有所抱怨。

Test suite failed to run

    Cannot find module 'react-xyz' from 'node_modules/foo-bar-ui/lib/ComponentC.js'

    Require stack:
      node_modules/foo-bar-ui/lib/ComponentC.js
      node_modules/foo-bar-ui/index.js'

直接的解决方案似乎是单独导出每个单独的组件,就像

lodash-es
所做的那样,例如
import isNil from 'lodash-es/isNil';
Node.js 子路径导出 似乎是完成这项工作的工具。但我发现 TypeScript、ESLint 和 Jest 都有问题,而且还有模块解析问题。

解决这个问题的最终推荐方法是什么?这看起来很简单,但奇怪的是我无法立即找到任何简单而简洁的解决方案。

javascript reactjs node.js jestjs typescript-module-resolution
1个回答
0
投票

最好涵盖两种情况:安装库时和未安装库时。 jest.mock 支持“虚拟”模块,允许您模拟不存在的模块,因此您的测试可以如下所示:

describe('ComponentC', () => {
  describe('with react-xyz', () => {
    beforeAll(() => {
      jest.mock('react-xyz', () => {
        // return some implementation
      }, { virtual: true });
    })
  });

  describe('without react-xyz', () => {
    beforeAll(() => {
      jest.mock('react-xyz', () => {
        // throw new Error('Cannot find module')
      }, { virtual: true });
    })
  });
})
© www.soinside.com 2019 - 2024. All rights reserved.