Issue
Not sure where to look for this error.
Using Typescript with React, and Jest and Enzyme for unit testing.
Package.json sample:
"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"
]
}
Running npm test results in:
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 <
Edit: It appears to be happening the first place where i use require
to load a static .svg
file. Why can it not handle that? Is there a way to ignore throwing this error when using require?
Solution
Jest doesn't use Webpack so it doesn't know how to load other file extensions than js/jsx. To add support for other extensions you need to write custom transformers. One of the transformers is a Typescript transformer which you have defined in your configuration in this fragment:
"transform": {
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
Now you need to add transformer for svg files. Let's extend your jest config
"transform": {
"^.+\\.tsx?$": "<rootDir>/node_modules/ts-jest/preprocessor.js",
"^.+\\.svg$": "<rootDir>/svgTransform.js"
},
and create the svgTransform.js file in your root directory with the following content
module.exports = {
process() {
return 'module.exports = {};';
},
getCacheKey() {
// The output is always the same.
return 'svgTransform';
},
};
Of course, it's a basic transformer that returns always the same value.
Link to the documentation: http://facebook.github.io/jest/docs/en/configuration.html#transform-object-string-string
Answered By - niba
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.