1

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?

1
  • 1
    sorry, your answer was correct! But I had to wait 10 minutes :) Thank you very much Commented Aug 9, 2019 at 13:38

1 Answer 1

1

Change your jest.config.js file to:

module.exports = {
  "roots": [
    "<rootDir>/src",
    "<rootDir>/tests"
  ],
  "transform": {
    "^.+\\.tsx?$": "ts-jest"
  },
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.