开玩笑测试:在打字稿组件导入中找不到模块

Jest test: Cannot find module, in typescript component import

我的样式化对象的路径是正确的,但不确定为什么会出现以下错误:

Cannot find module '../../shared/models' from 'Astronaut.tsx'

import { moonHoldings } from '../../shared/models';

我的简单 Jest 测试:

import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';

// @ts-ignore (works with .tsx)
import Astronaut from '../Astronaut.tsx';

describe('<Astronaut /> component', () => {
  describe('should render', () => {
    const wrapper = shallow(<Astronaut showLogo={true} />);
    it ('should render a component matching the snapshot', () => {
      const tree = toJson(wrapper);
      expect(tree).toMatchSnapshot();
      expect(wrapper).toHaveLength(1);
    });
  });
});

Astronaut 组件

import React from 'react';

import { moonHoldings } from '../../shared/models';  // <-- The problem
import { astronaut } from '../../styles'; // <-- This works

const { AstronautContainer, Heading } = astronaut;

interface LogoCheck {
  showLogo: boolean;
}

export default (showLogo: LogoCheck) =>  (
  <AstronautContainer>
    { showLogo.showLogo === true ? <Heading>{moonHoldings}</Heading> : null }
    <img src="static/astronaut.png" alt="astronaut" />
  </AstronautContainer>
);

我的 Jest 配置部分 Package.json

"jest": {
  "setupTestFrameworkScriptFile": "<rootDir>/jest.setup.js",
  "testPathIgnorePatterns": [
    "<rootDir>/.next/",
    "<rootDir>/node_modules/"
  ],
  "transform": {
    "\.(gql|graphql)$": "jest-transform-graphql",
    ".*": "babel-jest",
    "^.+\.js?$": "babel-jest"
  },
  "moduleFileExtensions": [
    "js",
    "json",
    "ts",
    "tsx"
  ],
  "modulePaths": [
    "<rootDir>/components/",
    "<rootDir>/pages/",
    "<rootDir>/shared/"
  ]
}

我的文件夹结构:

好的,我只是通过在 /shared 文件夹中创建一个索引文件然后以这种方式导出模型来解决这个问题(尽管它应该在没有索引文件的情况下仍然有效):

import { moonHoldings } from '../../shared';

和index.js:

export { moonHoldings, nomicsLink } from './copy';

您需要为您的玩笑测试做一些配置。 将此代码段添加到您的 package.json 应该允许您使用自定义名称并将其映射到您的实际文件夹:

"moduleNameMapper": {
  "^@fooBar/(.*)": "<rootDir>/src/barFoo/"
},