mocha由于绝对路径不断轰炸

ffx*_*sam 5 javascript mocha.js ecmascript-6 enzyme

我在使用 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();
  });
});
Run Code Online (Sandbox Code Playgroud)

ChipInput被导入时,该文件会导入一些具有绝对路径的内容,例如/lib/collections/tags,然后 Mocha 出错,因为它显然只执行相对路径。我如何让这个工作?

编辑:

实际错误:

Error: Cannot find module '/lib/collections/tags'
Run Code Online (Sandbox Code Playgroud)

发生这种情况是因为从/tests/ChipInput-test.js导入了ChipInput组件/client/components/Chips/index.js,其中包含以下几行:

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';
Run Code Online (Sandbox Code Playgroud)

ffx*_*sam 1

这是解决方案,很好又简单!

https://github.com/mantrajs/babel-root-slash-import

基本上,安装所述包:

npm install babel-root-slash-import --save-dev
Run Code Online (Sandbox Code Playgroud)

将插件添加到.babelrc

{
  "plugins": [
    "babel-root-slash-import"
  ]
}
Run Code Online (Sandbox Code Playgroud)

一切顺利。