Jest vs React:模块导出和“ Jest遇到意外令牌”

时间:2018-10-07 10:47:28

标签: javascript reactjs jestjs

我在让React和Jest一起工作时遇到了问题,这似乎很奇怪,因为我认为他们都来自相似的起源。我的问题与我正在测试的类的导出方式有关。

我有一个ArticleService类,当默认导出时,我可以在React中愉快地使用它:

class ArticleService {
    constructor(articles) {
        this.articles = articles;
        if (!this.articles) {
        this.articles =
            [//set up default data....
            ];
        }
    }
    getAll(){
        return this.articles;
    }
  }

//module.exports = ArticleService;//Need this for jest testing, but React won't load it
export default ArticleService;// Can't test with this but React will load it. 

这是在我的React应用程序中(从HomeComponent调用)的方式:

import ArticleService from './services/xArticleService';

并且被愉快地用作

const articles = (new ArticleService()).getAll();

但是我的测试无法运行。这是导入类文件的测试:

import ArticleService from "../services/xArticleService";

it('correctly gets all summaries', () => {
  var summaries = getFakeSummaryList();
  var testSubject = new ArticleService(summaries);
  var actual = testSubject.getAll();
  expect(actual.length).toEqual(10);
});

我明白了

FAIL src/tests/ArticleService.test.js
Test suite failed to run

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html

Details:

U:\...\src\tests\ArticleService.test.js:2
import ArticleService from "../services/xArticleService";
^^^^^^

SyntaxError: Unexpected token import

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

如果(在测试中)我猛扑

import ArticleService from "../services/xArticleService";

const ArticleService = require('../services/xArticleService');

并将xArticleService.js中的导出内容编辑为

module.exports = ArticleService;//Need this for jest testing, but React won't load it

然后执行测试,但是React不会加载它:

Attempted import error: './services/xArticleService' does not contain a default export (imported as 'ArticleService').

我有一个默认设置,使用create-react-app创建。我没有更改任何.babelrc。 谁能看到我要去哪里错了? 谢谢

更新:

我已对可接受的答案中的.babelrc进行了更改,以对此进行可能的重复,但此更改未更改输出。

0 个答案:

没有答案