user9945420
user9945420

Reputation:

configure Jest to support Typescript (NodeJs)

I would like to write tests for my Node/Express/Typescript application. Next to my src directory I added a tests directory with a app.spec.ts file with this demo content

import { App } from '../src/app';

describe('App', () => {
    let instance: App;

    beforeEach(() => {
        instance = new App();
    });

    it('creates an instance of App', async () => {
        expect(instance).toBeInstanceOf(App);
    });
});

Unfortunately Jest is not able to handle Typescript.

Details:

C:...\tests\app.spec.ts:1 ({"Object. ":function(module,exports,require,__dirname,__filename,global,jest){import { App } from '../src/app';

SyntaxError: Unexpected token { at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17) at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)

This is my package.json (relavant fields)

{
  "scripts": {
    "start": "node dist/app.js",
    "dev": "nodemon src/app.ts",
    "build": "tsc -p .",
    "test": "jest",
    "testWithCoverage": "jest --coverage"
  },
  "devDependencies": {
    "@types/express": "^4.17.0",
    "@types/jest": "^24.0.17",
    "@types/node": "^12.6.9",
    "@typescript-eslint/eslint-plugin": "^1.13.0",
    "@typescript-eslint/parser": "^1.13.0",
    "eslint": "^5.16.0",
    "eslint-config-airbnb-base": "^13.2.0",
    "eslint-plugin-import": "^2.18.2",
    "jest": "^24.8.0",
    "nodemon": "^1.19.1",
    "ts-jest": "^24.0.2",
    "ts-node": "^8.3.0",
    "typescript": "^3.5.3"
  }
}

Further I created a jest.config.js file with that content

module.exports = {
    roots: [
        './tests',
    ],
    moduleFileExtensions: [
        'ts',
        'tsx',
        'js',
        'jsx',
    ],
};

Does someone know what's missing here?

Upvotes: 1

Views: 1933

Answers (1)

Peter
Peter

Reputation: 2927

Change your jest.config.js file to:

module.exports = {
  "roots": [
    "<rootDir>/src",
    "<rootDir>/tests"
  ],
  "transform": {
    "^.+\\.tsx?$": "ts-jest"
  },
}

Upvotes: 1

Related Questions