Jest无法从npm链接模块转换导入

时间:2017-06-07 13:12:28

标签: javascript babel jest lerna

我有一个包含多个模块的项目(使用Lerna),我想使用Jest来运行测试。但是,当我测试使用共享模块的代码(通过Lerna的npm链接模块)时,似乎Babel未正确应用,我收到以下错误:

# split into train and test
from sklearn import cross_validation
data_train, data_test, labels_train, labels_test = cross_validation.train_test_split(
    data.ApiCall,
    data.Malware, 
    test_size=0.25, 
    random_state=42)

print (data_train[:10])

### text vectorization--go from strings to lists of numbers
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_selection import SelectPercentile, f_classif

vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5)
data_train_transformed = vectorizer.fit_transform(data_train)
data_test_transformed  = vectorizer.transform(data_test)

print (data_train_transformed[:10])


# slim the data for training and testing
selector = SelectPercentile(f_classif, percentile=10)
selector.fit(data_train_transformed, labels_train)
data_train_transformed = selector.transform(data_train_transformed).toarray()
data_test_transformed  = selector.transform(data_test_transformed).toarray()

print (data_train_transformed[:10])


from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score

clf = GaussianNB()
clf.fit(data_train_transformed, labels_train)
predictions = clf.predict(data_test_transformed)

print (accuracy_score(labels_test, predictions))

我的项目结构如下:

SyntaxError: Unexpected token import

- my-project |- shared |- native |- web web需要native模块。当我进入shared目录并在Jest中运行本地测试时,一切正常。如果我在shared目录中运行Jest测试,只要我在web中包含某些内容,就会出现上述错误。

这是一个导致错误的超级简单测试:

shared

我的import { util } from 'shared'; it('returns false if not prod', () => { expect(util.isProd()).toBe(false); }); 看起来像这样:

.babelrc

我尝试了所有可以找到的东西,包括:

  • 不同的Babel配置,包括具有{ "presets": [ "env", "flow", "react" ], "plugins": [ "flow-react-proptypes", "transform-object-rest-spread", "transform-class-properties" ] } 预设且为测试环境启用es2015的配置
  • 手动设置babel-jest的modules选项
  • 如上所述,Jest可以在transform模块中执行,因此,Jest和shared也会安装在那里。

1 个答案:

答案 0 :(得分:5)

我必须在transformIgnorePatterns模块的package.json中更改Jest的web配置选项。

{
    "jest": {
        "transformIgnorePatterns": [
            "<rootDir>/node_modules/(?!shared|another)"
        ]
    },
}