首页 文章

使用React,Typescript和ES6进行Jest测试

提问于
浏览
2

我在使用ES6编写的Jest(v16.0.1)测试测试使用Typescript(v2.0.3)编写的React组件时遇到了一些问题 .

我正在使用ts-jest(v0.1.8)预处理器和package.json的相关部分看起来像

"jest": {
    "scriptPreprocessor": "<rootDir>/node_modules/ts-jest/preprocessor.js",
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ]
  }

但是当我运行测试时,我得到:

FAIL  app/components/__tests__/TestTotalNumberOfTeapots.js
  ● Test suite failed to run

    /Users/aaron/Desktop/teabot_stats/app/components/__tests__/TestTotalNumberOfTeapots.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
                                                                                             ^^^^^^
    SyntaxError: Unexpected token import

      at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:284:10)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.673s
Ran all test suites.

我的测试看起来像

import React from 'react';
import TotalNumberOfTeapots from '../TotalNumberOfTeapots.tsx';
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  const tree = renderer.create(
    <TotalNumberOfTeapots numberOfTeapots='1' />
  ).toJSON();
  expect(tree).toMatchSnapshot();
});

我假设我需要一个设置,我的组件使用ts-jest从Typescript转换为ES5,我的测试在使用babel-jest之前从ES6转换为ES5,然后Jest读取它们但我不确定如何?

1 回答

  • 5

    管理这个工作,需要编写我自己的预处理器:

    const tsc = require('typescript');
    const babelJest = require('babel-jest');
    
    module.exports = {
      process(src, path) {
        if (path.endsWith('.ts') || path.endsWith('.tsx')) {
          return tsc.transpile(
            src,
            {
              module: tsc.ModuleKind.CommonJS,
              jsx: tsc.JsxEmit.React,
            },
            path,
            []
          );
        }
        if (path.endsWith('.js') || path.endsWith('.jsx')) {
            return babelJest.process(src, path);
        }
        return src;
      },
    };
    

    并更新我的package.json以具有:

    "jest": {
        "scriptPreprocessor": "preprocessor.js",
        "moduleFileExtensions": ["js", "jsx", "json", "ts", "tsx"]
      },
    

相关问题