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

时间:2019-01-24 04:38:25

标签: javascript reactjs typescript jestjs next.js

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

  

无法从“ Astronaut.tsx”中找到模块“ ../../ shared / models”

     

从'../../shared/models'导入{moonHoldings};

我简单的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/"
  ]
}

我的文件夹结构:

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

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

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

enter image description here

还有index.js:

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

答案 1 :(得分:1)

您的笑话测试不需要做任何配置。 将此代码段添加到您的package.json中应该可以使您使用自定义名称并将其映射到您的实际文件夹:

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