Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest test: Cannot find module, in typescript component import

The path to my styled objects is correct, however not sure why I'm getting the following error:

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

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

My simple Jest test:

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

The Astronaut component

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

The Jest config section of my 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/"
  ]
}

And my folder structure:

enter image description here

enter image description here

like image 988
Leon Gaban Avatar asked Jan 24 '19 04:01

Leon Gaban


2 Answers

You need to do little configuration for your jest test. Adding this snippet to your package.json should allow you to take your custom name and map it to your actual folder:

"moduleNameMapper": {
  "^@fooBar/(.*)": "<rootDir>/src/barFoo/$1"
},
like image 128
Azeem Chauhan Avatar answered Sep 20 '22 14:09

Azeem Chauhan


Ok I just fixed this by created an index file inside of the /shared folder and then exporting out the models that way (Though it should have still worked without the index file):

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

enter image description here

And the index.js:

export { moonHoldings, nomicsLink } from './copy';
like image 33
Leon Gaban Avatar answered Sep 19 '22 14:09

Leon Gaban