2017-10-17 27 views
3

不確定在哪裏查找此錯誤。Jest測試失敗:SyntaxError:意外標記<

使用Typescript和React,以及Jest和Enzyme進行單元測試。

的package.json樣本:

"scripts": { 
    "start": "node server.js", 
    "bundle": "cross-env NODE_ENV=production webpack -p", 
    "test": "jest" 
    }, 
    "jest": { 
    "transform": { 
     "^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js" 
    }, 
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", 
    "moduleFileExtensions": [ 
     "ts", 
     "tsx", 
     "js", 
     "json" 
    ] 
    } 

運行NPM測試結果:

FAIL src/components/Component.test.tsx 

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){<?xml version="1.0" encoding="UTF-8"?> 
                          ^

    SyntaxError: Unexpected token < 

編輯:這似乎是發生在這裏我使用require加載靜態.svg文件的第一個地方。爲什麼它不能處理?有沒有辦法忽略在使用require時拋出這個錯誤?

+0

嘗試刪除'xml'標記並僅包含以下'svg'標記 –

回答

3

Jest不使用Webpack,所以它不知道如何加載其他文件擴展名比js/jsx。要添加對其他擴展的支持,您需要編寫自定義轉換器。其中變壓器是你已經在你的配置在這個片段中定義的打字稿變壓器:

"transform": { 
    "^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js" 
}, 

現在,你需要添加變壓器SVG文件。讓我們來擴展你的笑話配置

"transform": { 
     "^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js", 
     "^.+\\.svg?$": "<rootDir>/svgTransform.js" 
    }, 

,並具有以下內容

module.exports = { 
    process() { 
    return 'module.exports = {};'; 
    }, 
    getCacheKey() { 
    // The output is always the same. 
    return 'svgTransform'; 
    }, 
}; 

當然建立在你的根目錄下的文件svgTransform.js,這是一個基本的變壓器總是返回相同的值。

鏈接到本文檔:http://facebook.github.io/jest/docs/en/configuration.html#transform-object-string-string