网站搜索

javascript - Jest 测试:在 TypeScript 组件导入中找不到模块


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

无法从 'Astronaut.tsx' 找到模块 '../../shared/models'

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);
    });
  });
});

宇航员组件

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>
);

我的 Package.json 的 Jest 配置部分

"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/"
  ]
}

以及我的文件夹结构:

答案#1

你只需要为你的 jest 测试做少量配置。将此片段添加到你的 package.json 中应该允许你将自定义名称映射到实际的文件夹:

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

答案#2

在我的情况下,我在测试文件中的许多实例中都遇到了这个错误,解决方法是在我的 jest.config 文件中的 moduleNameMapper 选项中使用基于文件路径的映射。这有助于我们将绝对路径映射到相应的相对路径。

例如,如果你收到此错误 -

  ● Test suite failed to run
                                                                                                                                                             
    Cannot find module 'jsroot/io' from 'src/some-file.ts'

添加这个应该可以 -

moduleNameMapper: {
    // 'absolute-path': 'relative-path'
    'jsroot/io': '<rootDir>/node_modules/jsroot/',
},

其中 <rootDir> 是包含你的 Jest 配置文件或 package.json 的目录的根目录。

相关文章