使用Jest和Webpack别名进行测试

我希望能够在使用jest时使用webpack别名来解析导入,并且最好参考webpack.aliases以避免重复。

开玩笑的conf:

  "jest": {

"modulePaths": ["src"],

"moduleDirectories": ["node_modules"],

"moduleNameMapper": {

"^@shared$": "<rootDir>/shared/",

"^@components$": "<rootDir>/shared/components/"

}

},

Webpack别名:

exports.aliases = {

'@shared': path.resolve(paths.APP_DIR, 'shared'),

'@components': path.resolve(paths.APP_DIR, 'shared/components'),

};

进口:

import Ordinal from '@shared/utils/Ordinal.jsx';

import Avatar from '@components/common/Avatar.jsx';

由于某种原因,@导致了问题,因此将其删除(使用别名和导入)时,可以找到sharedcomponents仍然无法解决。

 FAIL  src/shared/components/test/Test.spec.jsx

● Test suite failed to run

Cannot find module '@shared/utils/Ordinal.jsx' from 'Test.jsx'

我尝试使用jest-webpack-alias,babel-plugin-module-resolver和Jest / Webpack

docs

回答:

这似乎已解决。

以下是有效的设置:

"jest": "~20.0.4"

"webpack": "^3.5.6"

"jest": {

"moduleNameMapper": {

"^@root(.*)$": "<rootDir>/src$1",

"^@components(.*)$": "<rootDir>/src/components$1",

}

}

const paths = {

APP_DIR: path.resolve(__dirname, '..', 'src'),

};

exports.resolveRoot = [paths.APP_DIR, 'node_modules'];

exports.aliases = {

'@root': path.resolve(paths.APP_DIR, ''),

'@components': path.resolve(paths.APP_DIR, 'components'),

};

以上是 使用Jest和Webpack别名进行测试 的全部内容, 来源链接: utcz.com/qa/417939.html

回到顶部