【问题标题】:Can't find module 'react' while trying to test a component尝试测试组件时找不到模块“反应”
【发布时间】:2019-09-22 20:48:57
【问题描述】:

我正在尝试向我的应用程序添加一些测试,但是当我安装react-testing-library 和jest-dom 时,我编写了这个测试,测试是否调用了componentDidMount:

import { render } from "react-testing-library";

import { QuestionContainer } from "../containers/QuestionContainer";

it("should call componentDidMount", () => {
  const cDM = jest.spyOn(QuestionContainer.prototype, "componentDidMount");

  render(QuestionContainer);

  expect(cDM).toHaveBeenCalled(1);
});

但我收到此错误:

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

However, Jest was able to find:
    '../containers/QuestionContainer.js'

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'].

我不认为文件扩展名有问题..

【问题讨论】:

  • 您需要添加import React from 'react'
  • 已经试过了。
  • 你跑npm install了吗??
  • 你能检查一下 package.json 中是否存在 'react' 依赖项吗?还要检查一下文件 QuestionContainer 的扩展名是 .js 还是 .jsx
  • 愚蠢的错误,我在根文件夹而不是 React 应用程序所在的客户端文件夹中安装了一些依赖项。

标签: javascript reactjs testing react-testing-library


【解决方案1】:

您需要安装react-test-renderer:

yarn add react-test-renderer // 或将其添加到您的开发依赖项中!

【讨论】:

    猜你喜欢
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2022-08-15
    • 2013-08-17
    • 2020-06-22
    • 1970-01-01
    相关资源
    最近更新 更多