我在使用 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
,然后 Mocha 出错,因为它显然只执行相对路径。我如何让它工作?
编辑:
实际错误:
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 允许通过环境变量或编程方式设置基数,允许不需要前导斜杠的简单绝对路径(require("my/module");
vs 要求(“/我的/模块”);
)。
我使用 gulp 作为 taskrunner,所以我的首选技术是使用 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
关于javascript - 由于绝对路径, Mocha 不断轰炸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37221010/