摩卡由于绝对路径而不断轰炸

Mocha keeps bombing due to absolute paths

本文关键字:路径 卡由 于绝 摩卡      更新时间:2023-09-26

我在使用 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"
  ]
}

而且很好。