moduleDirectories 键无法导入我的测试工具

IT技术 javascript reactjs unit-testing jestjs react-testing-library
2021-05-12 03:52:23

我想用 Jest 和@testing-lib/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作为绝对路径而不是相对路径导入

1个回答

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

如果你有这个文件夹结构

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

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

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

然后utils/你想要的.js文件中test-utils.js然后您可以从test-utils测试中导入

因此,关键在于您导出的module的名称必须是.js文件的名称您放入的文件夹moduleDirectories必须包含此.js文件。