摩卡由于绝对路径而不断轰炸
Mocha keeps bombing due to absolute paths
我在使用 Enzyme 和 Mocha 来测试我的 React 项目时遇到了很多麻烦。我有一个这样的测试:
import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import { ChipInput} from '../client/components/Chips';
describe('<ChipInput />', _ => {
it('rocks', done => {
done();
});
});
当导入ChipInput
时,该文件会导入具有绝对路径的内容,例如 /lib/collections/tags
,然后摩卡出错了,因为它显然只做相对路径。我如何让它工作?
编辑:
实际错误:
Error: Cannot find module '/lib/collections/tags'
发生这种情况是因为/tests/ChipInput-test.js
从 /client/components/Chips/index.js
导入ChipInput
组件,该组件具有以下行:
import React from 'react';
import {
MapsLocalOffer as TagIcon,
ImageRemoveRedEye as InsightIcon,
EditorInsertChart as TestIcon,
SocialPerson as UserIcon,
} from 'material-ui/svg-icons';
import { Tag } from '/lib/collections/tags'; // error thrown here
import { Insight } from '/lib/collections/insights';
// import { Test } from '/lib/collections/tests';
import Chip from './Chip';
import ChipDisplay from './ChipDisplay';
import ChipInput from './ChipInput';
import * as chipTypes from './chip-types';
对于任何从谷歌来到这里的人来说,虽然ffxsam的答案会起作用,但有很多方法可以做到这一点。Node的需求允许通过环境变量或以编程方式设置基数,允许不需要前导斜杠的简单绝对路径(require("my/module");
与require("/my/module");
(。
我使用 gulp 作为任务执行器,所以我的首选技术是使用 app-module-path
在我的 gulpfile 顶部执行以下操作(只要您还没有遇到任何绝对require
,这将在任何地方工作(:
require('babel-core/register'); //for mocha to use es6
require('app-module-path').addPath(__dirname + '/src'); //set root path
//I also use webpack to pull in other extensions, so I
//want mocha to noop out on them
require.extensions['.css'] = _.noop;
require.extensions['.scss'] = _.noop;
require.extensions['.png'] = _.noop;
require.extensions['.jpg'] = _.noop;
require.extensions['.jpeg'] = _.noop;
require.extensions['.gif'] = _.noop;
有关更完整的概要,请查看github用户branneman的要点:https://gist.github.com/branneman/8048520
这已经有一段时间了,但我想在这里分享我的解决方案,以防万一,上述所有解决方案都不适用于您的具体情况。我正在寻找一种解决方案来修复我们的单元测试,该测试失败了"错误:找不到模块'组件/共享/xyz',我们的"组件"文件夹位于"客户端/src"文件夹下,因此我想出了以下适合我们的解决方案。
npm install babel-plugin-module-resolver --save-dev
{
'plugins': [
'babel-plugin-module-resolver',
{ 'root': ['client/src'] }
]
}
这是解决方案,很好,很简单!
https://github.com/mantrajs/babel-root-slash-import
基本上,安装所述软件包:
npm install babel-root-slash-import --save-dev
将插件添加到.babelrc
:
{
"plugins": [
"babel-root-slash-import"
]
}
而且很好。
- 在Android网络应用程序中查找SD卡的路径
- 摩卡由于绝对路径而不断轰炸
- 以编程方式确定由 SVG 路径生成的形状
- 如何将值传递到由chrome.tabs.create打开的新选项卡
- 将导航选项卡样式类设置为活动,如果当前在该路由中 反应反应路由器.
- Java 脚本文件路径未由 SharePoint 标识
- 拉斐尔SVG路径的一部分卡在原地
- 卡图.js如何通过路径 ID 获取元素
- PhoneGap安卓应用程序需要获取外部SD卡路径,但它只返回内部SD卡路径
- jQuery 选项卡动画暂停并由控制器播放
- 将变量创建到路径JSON是由jQuery执行的操作
- 如何调试“错误:承诺被拒绝,无理由或虚假理由”;在摩卡测试中
- 查找以前由窗口打开的窗口.在chrome的新选项卡中打开
- 如何消除由相对路径引起的重复需求?
- 获得所有的WebRequest由选定的选项卡在Chrome a扩展
- Fullcalendar无法填充由选项卡隐藏的页面
- 如何禁用由html创建的特定dijit contentPane选项卡
- Angularjs:当页面加载时,(对于第一个选项卡)触发通常由ngClick在按钮上触发的方法
- AngularJS:选项卡窗格的HTML标记各不相同,我希望它们是动态创建的,并填充由工厂服务提供的数据
- JQuery.UI.选项卡由TabID默认选择