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

11

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

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

我的文件夹结构:

在此输入图片描述

在此输入图片描述

3个回答

5
你需要对Jest测试进行一些配置。将下面的代码片段添加到你的package.json中,可以让你使用自定义名称并将其映射到实际文件夹:
"moduleNameMapper": {
  "^@fooBar/(.*)": "<rootDir>/src/barFoo/$1"
},

1
在我的情况下,在我的测试文件中有很多实例出现了这个错误,解决方法是在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的目录根目录。


1

我刚刚通过在/shared文件夹中创建索引文件并以这种方式导出模型来修复了此问题(尽管没有索引文件仍然应该可以正常工作):

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

enter image description here

而且index.js:

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

你是否已经在 Jest 测试文件中导入了它们? - Makuna
4
这似乎更像是一种变通方法,而不是一个答案。 - mikemaccana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接