首页 > 解决方案 > 无法从 'index.js' 中找到模块 'react' - (node_modules/jest-resolve/build/index.js:259:17)

问题描述

我的项目创建过程(这是一个create-react-app打字稿版本模板:

  25 npx create-react-app test --template typescript
  26 cd test
  27 ls
  28 npm install --save-dev react-test-renderer
  29 npm test
  30 npm test
  31 node --version
  32 npx create-react-app --version
  33 npm install antd -g
  34 npm test

Jest在 package-lock.json 中的版本

    "@jest/core": {
      "version": "24.9.0",

我的 node.js 版本是

v12.19.0

create-react-app 版本是

npx create-react-app --version
3.4.1

antd版本是

antd@4.6.6

文件:App.test.tsxtesting file

import React from 'react';
import { render } from '@testing-library/react';
import App from './App';
import renderer from 'react-test-renderer';
import MyButton from './components/button';


it('renders a snapshot', () => {
  const tree = renderer.create(<App/>).toJSON();
  expect(tree).toMatchSnapshot();
});


it('MyButton', () => {
  const tree = renderer.create(<MyButton/>).toJSON();
  expect(tree).toMatchSnapshot();
});

我的antd源文件

import React from 'react'
import { Button } from 'antd';

const MyButton = () => {
  const [value, setValue] = React.useState('')

  // The event type is a "ChangeEvent"
  // We pass in "HTMLInputElement" to the input
  function onChange(e: React.ChangeEvent<HTMLInputElement>) {
    setValue(e.target.value)
  }

  return <Button></Button>
}

export default MyButton;

当我跑的时候npm test,我得到了这个

 FAIL  src/App.test.tsx
  ● Test suite failed to run

    Cannot find module 'react' from 'index.js'

    However, Jest was able to find:
        'components/button.tsx'

    You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['web.js', 'js', 'web.ts', 'ts', 'web.tsx', 'tsx', 'json', 'web.jsx', 'jsx', 'node'].

    See https://jestjs.io/docs/en/configuration#modulefileextensions-array-string

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
      at Object.<anonymous> (../../../node_modules/antd/lib/affix/index.js:26:37)

标签: node.jstypescriptjestjscreate-react-appantd

解决方案


推荐阅读