【问题标题】:moduleDirectories key does not make it possible to import my test utilsmoduleDirectories 键无法导入我的测试工具
【发布时间】:2019-12-20 16:43:15
【问题描述】:

我想用 Jest 和 @testing-lib/react-native 测试我的 Expo React Native 应用程序。

我在package.json 中设置了以下内容。

"jest": {
    "preset": "jest-expo",
    "moduleDirectories": [
      "node_modules",
      "test-utils"
    ]
  },

我的文件夹结构如下:

├──node_modules/
├──test-utils/
├──src/
└──package.json

src/ 包含测试文件。我正在src/index.test.js 使用这个简单的测试来测试我的配置:

import { assert } from 'test-utils';

const sum = (a, b) => a + b;

describe('sum', () => {
  assert({
    given: 'two numbers',
    should: 'add the numbers',
    actual: sum(1, 3),
    expected: 4,
  });
});

asserttest-utils/index.js 中的位置:

const assert = ({
  given = undefined,
  should = '',
  actual = undefined,
  expected = undefined,
} = {}) => {
  it(`given ${given}: should ${should}`, () => {
    expect(actual).toEqual(expected);
  });
};

export { assert };

如果我运行测试,我会收到错误:

Cannot find module 'test-utils' from 'index.test.js'

这是为什么呢?我的意思是我已经配置了moduleDirectories 键? ???你怎么能解决这个问题?我真的很想能够将assert 作为绝对路径而不是相对路径导入。

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs react-testing-library


    【解决方案1】:

    我找到了解决方案。文档目前很糟糕。

    如果你有这个文件夹结构

    ├──node_modules/
    ├──src/
    ├──utils/
    └──package.json
    

    然后你想像这样命名你的模块目录:

    "jest": {
      "preset": "jest-expo",
      "setupFilesAfterEnv": [
        "@testing-library/react-native/cleanup-after-each"
      ],
      "moduleDirectories": [
        "node_modules",
        "utils"
      ]
    },
    

    然后utils/内你想拥有.js文件test-utils.js。然后你可以在你的测试中从test-utils 导入。

    因此,关键是您导出的模块的名称必须是.js 文件的名称。而您放入moduleDirectories 的文件夹必须包含这个.js 文件。

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 2021-07-26
      • 1970-01-01
      • 2018-11-04
      • 2020-09-03
      • 2019-05-23
      • 2021-06-12
      • 2017-11-23
      • 1970-01-01
      相关资源
      最近更新 更多