我想使用 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,
});
});
其中 assert
位于 test-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
作为绝对路径而不是相对路径导入。
最佳答案
我找到了解决方案。目前的文档很糟糕。
如果你有这个文件夹结构
├──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
文件。
关于javascript - moduleDirectories 键无法导入我的测试实用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57489370/