【问题标题】:NX React - how to create default mock for libraryNX React - 如何为库创建默认模拟
【发布时间】:2021-11-04 08:35:16
【问题描述】:

您如何为您的应用程序使用的库创建手动模拟?

我正在尝试在 jest documentation 中进行范围模拟,但没有运气。

示例:

my-workspace
├── __mocks__
│   └── @my-workspace/my-lib.ts
├── apps
│   ├── my-app
│       └── index.ts
├── libs
│   ├── my-lib
│       └── index.ts
...

【问题讨论】:

    标签: reactjs jestjs nrwl nomachine-nx


    【解决方案1】:

    nx 工作区中的libs 可以像常规 node_modules 一样导入,这要归功于它的TS path mapping(检查您的tsconfig.base.json 以查看@workspace-scope/my-lib 是如何解决的)。

    但是,您的 lib 并不是一个节点模块(即使您发布它),应该使用“用户模块”开玩笑模式来模拟:https://jestjs.io/docs/manual-mocks#mocking-user-modules

    改为将模拟移动到libs/my-lib/__mocks__/index.ts(如果需要,您可以将模拟拆分为多个文件,只需确保从索引文件中导出您需要模拟的任何内容)然后在spec 文件中手动调用jest.mock('@workspace-scope/my-lib');你在哪里导入你的 lib 函数:

    // libs/my-lib/__mocks__/index.ts
    export function foo(): string {
      return 'foo';
    }
    
    // apps/my-app/.../some-test.spec.ts
    import { foo } from '@workspace-scope/my-lib';
    
    // manually mock the user module: make sure the path matches the import above
    jest.mock('@workspace-scope/mylib');
    // --> now when you invoke foo() in this file, jest should invoke "foo" exported from "libs/my-lib/__mocks__/index.ts" instead
    
    describe('test foo', () => {
      test('returns "foo"', () => {
        expect(foo()).toBe('foo');
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-18
      • 2021-05-25
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 2022-10-07
      相关资源
      最近更新 更多