gpt4 book ai didi

javascript - 在 typescript 组件导入中开 Jest 测试 : Cannot find module,

转载 作者:行者123 更新时间:2023-11-30 19:52:30 25 4
gpt4 key购买 nike

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

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

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

我的文件夹结构:

enter image description here

enter image description here

最佳答案

你需要为你的 Jest 测试做一些配置。将此代码段添加到您的 package.json 应该允许您使用自定义名称并将其映射到您的实际文件夹:

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

关于javascript - 在 typescript 组件导入中开 Jest 测试 : Cannot find module,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54339452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com