2016-10-16 45 views
2

我在使用ES6編寫的Jest(v16.0.1)測試測試用Typescript(v2.0.3)編寫的React組件時遇到了一些問題。使用React,Typescript和ES6進行Jest測試

我使用的是TS-笑話(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(); 
}); 

我想我需要在我的部件由打字稿transpiled的設置使用ts-jest的ES5和我的測試在Jest讀取之前使用babel-jest從ES6轉換爲ES5,但我不確定如何?

回答

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"] 
    }, 
+0

碰上 「未找到preprocessor.js」,變化它到 ''scriptPreprocessor「:」./preprocessor.js「' –

+0

@ObooChin你必須在'package.json'旁邊創建'preprocessor.js'文件 –

相關問題