代码之家  ›  专栏  ›  技术社区  ›  Leon Gaban

jest测试:在typescript组件导入中找不到模块

  •  0
  • Leon Gaban  · 技术社区  · 6 年前

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

    找不到“astronet.tsx”中的模块“.../../shared/models”

    从'../../shared/models'导入moonholdings';

    我简单的笑话测试:

    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-config部分

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

    我的文件夹结构:

    enter image description here

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  0
  •   Leon Gaban    6 年前

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

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

    enter image description here

    以及index.js:

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