【问题标题】:React & Jest: Cannot find module from test fileReact and Jest:无法从测试文件中找到模块
【发布时间】:2016-09-15 10:09:43
【问题描述】:

app/__tests__ 目录中为 Redux 操作 ('App.js') 设置 Jest 测试 ('App-test.js'):

这是 App.js 的标头:

jest.unmock('../../modules/actions/App.js')

import React from 'react'
import ReactDOM from 'react-dom'
import TestUtils from 'react-addons-test-utils'

import * as App from '../../modules/actions/App.js'

app/ 中有一个模块config.js。正在将其导入到需要的地方。

问题是,当我运行我的 Jest 测试(例如 App-test.js)时,它正在寻找配置而不是找到它:

 FAIL  __tests__/actions/App-test.js
Runtime Error
Error: Cannot find module 'config' from 'User.js'

<i>User.js</i> 正在导入config,如下所示: import config from 'config'

<i>User.js</i> 是另一个正在使用的操作App.js

有什么想法吗?

【问题讨论】:

  • 发布更多代码,如果没有更多代码来查看需要修复的内容,有点令人困惑。可能与您使用 export 的方式有关。
  • 可能是错字,但我不确定...尝试将 ./ 添加到配置路径,这样它将是 import config from './config';也许 jest 正在尝试访问 node_modules 中名为 config 的包?我不知道您使用的是什么版本的 jest,但自 v15.0.0 以来自动模拟已禁用 - github.com/facebook/jest/blob/master/CHANGELOG.md#jest-1500

标签: javascript reactjs redux jestjs


【解决方案1】:

您应该指定模块位置,否则 Node.js 会尝试为您猜测位置,例如:

node_modules/config.js
node_modules/config/index.js
node_modules/config/package.json

您的代码中的问题是假设节点将在所需位置查找文件,正如您在我在前几行中提供的算法中看到的那样。

要解决此问题,您必须在 User.js 文件中指定位置,例如,检查假设的文件组织:

/
/config.js
/app
/app/User.js

然后,您将在 User.js 中导入:

import config from '../config.js'

文件config.js相对于User.js,位于父目录中。

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 2018-02-20
    • 1970-01-01
    相关资源
    最近更新 更多