typescript-jest-example
typescript-jest-example copied to clipboard
Add example with external node modules
Because it breaks when you add any external module.
For example, run npm i chalk
, then edit src/calc.ts:
import chalk from 'chalk'
export function add(x: number, y: number): number {
console.log(chalk.red('Test'))
return x + y;
}
export function mul(x: number, y: number): number {
return x * y;
}
Then try to run npm test
and you're getting:
FAIL test/calc.test.ts
● 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 plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" 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 with 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/VITA/Documents/typescript-jest-example/node_modules/chalk/source/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import ansiStyles from '#ansi-styles';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import chalk from 'chalk'
| ^
2 |
3 | export function add(x: number, y: number): number {
4 | console.log(chalk.red('Test'))
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
at Object.<anonymous> (src/calc.ts:1:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.647 s, estimated 4 s
Ran all test suites.