Jest не может запустить .tsx файлы (CRA 2, энзим) - PullRequest
0 голосов
/ 23 июня 2019

Я не могу использовать 'npm test' в моем проекте ts CRA 2, потому что jest не удается обработать .tsx. Я следовал этому [руководству по установке] (https://thetrevorharmon.com/blog/configuring-jest-and-enzyme-in-create-react-app-on-typescript).

Я пытаюсь использовать ts-jest для преобразования файлов .tsx, но это не работает.

Я обнаружил, что изменение параметра "jsx" в файле tsconfig.json на "реагировать" с "сохранить" позволит jest работать без ошибок. К сожалению, это несовместимо со скриптом «npm run», поставляемым с CRA 2, так как он вернет тип jsx обратно в «preserve».

jest config:

module.exports = {
  roots: ['<rootDir>/src'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};

тестовый файл:

import React from 'react';
import { shallow } from 'enzyme';
import AboutPage from 'pages/AboutPage';

describe('MyComponent', () => {
  it('should render correctly with no props', () => {
    const component = shallow(<AboutPage />);

    expect(component).toMatchSnapshot();
  });
});

TSconfig

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "baseUrl": "./src"
  },
  "include": [
    "src"
  ]
}

Все тесты должны пройти, но вместо этого появятся следующие сообщения об ошибках Jest:

 FAIL  src/__tests__/AboutPage.test.tsx
  ● 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 p
lain JavaScript.


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

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgn
orePatterns" 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 wit
h 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:

    /Users/josh/Repos/welfare-react-capacitor/src/__tests__/AboutPage.test.tsx:11
            var component = enzyme_1.shallow(<AboutPage_1.default />);
                                             ^

    SyntaxError: Unexpected token <

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransf
ormer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25
)

После добавления Babel-Jest:

    SyntaxError: /Users/josh/Repos/welfare-react-capacitor/src/__tests__/AboutPage.test.tsx: Unexpec
ted token (7:30)

       5 | describe('MyComponent', () => {

       6 |   it('should render correctly with no props', () => {
    >  7 |     const component = shallow(<AboutPage />);
         |                               ^
       8 |
       9 |     expect(component).toMatchSnapshot();
      10 |   });

      at Parser.raise (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:6344:17)
      at Parser.unexpected (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:7659:16
)
      at Parser.parseExprAtom (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8828
:20)
      at Parser.parseExprSubscripts (node_modules/@babel/core/node_modules/@babel/parser/lib/index.j
s:8413:23)
      at Parser.parseMaybeUnary (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:83
93:21)
      at Parser.parseExprOps (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8280:
23)
      at Parser.parseMaybeConditional (node_modules/@babel/core/node_modules/@babel/parser/lib/index
.js:8253:23)
      at Parser.parseMaybeAssign (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:8
200:21)
      at Parser.parseExprListItem (node_modules/@babel/core/node_modules/@babel/parser/lib/index.js:
9475:18)
      at Parser.parseCallExpressionArguments (node_modules/@babel/core/node_modules/@babel/parser/li
b/index.js:8620:22)

Ответы [ 2 ]

0 голосов
/ 23 июня 2019

удалось решить проблему, установив babel-jest и используя этот файл .babelrc:

{
  "presets":["@babel/preset-react", "@babel/preset-env"]
}

Те будут успешно работать , но: абсолютные пути не работают для операторов импорта. Я полагаю, что это можно исправить еще с некоторыми конфигурациями.

Редактировать: исправлена ​​проблема с импортом, добавив это в jest config:

  modulePaths: ['<rootDir>/src']

0 голосов
/ 23 июня 2019

Похоже, вам не хватает плагина babel-loader.

...