Mocha + TypeScript: Cannot use import statement outside a module

前端 未结 3 1550
我寻月下人不归
我寻月下人不归 2021-01-04 08:13

I was watching this video in order to learn how to add some simple tests to my Express routes but I am getting all kind of errors while executing a test. The error is:

相关标签:
3条回答
  • 2021-01-04 08:19

    Had the same issue and almost gave up using Mocha with TypeScript (in our case Angular 9).

    This is what helped me:

    In tsconfig.json:

    Replaced this:

    "module": "esnext", 
    

    with this:

    "module": "commonjs",
    

    Also here I found a working example of Mocha with TypeScript and used the tsconfig file from there to compare with mine: https://medium.com/@RupaniChirag/writing-unit-tests-in-typescript-d4719b8a0a40

    0 讨论(0)
  • 2021-01-04 08:27

    I've recently hit this problem a few times in a project I'm working on.

    The project contains many smaller modules which are all written in TypeScript and compiled before being committed. I have (clearly at least couple of times by the fact this link was already purple) somehow managed to commit my module without compiling. This resulted in the error when mocha tried to execute the .js version of a dependency which wasn't committed to version control.

    Building the dependency, committing and updating the packages fixed my issue. Hopefully this helps someone else out in a similar position to me!

    0 讨论(0)
  • 2021-01-04 08:31

    I was able to test thanks to the @types/chai-http – Can't use ES6 import GitHub issue's answer.

    I added a second TypeScript configuration file tscconfig.testing.json with the following information:

    {
        "compilerOptions": {
          "module": "commonjs",
          "target": "es2015",
          "lib": ["es2017"],
          "declaration": false,
          "noImplicitAny": false,
          "removeComments": true,
          "inlineSourceMap": true,
          "moduleResolution": "node"
        },
        "include": ["scripts/**/*.ts", "src/**/*.ts", "node_modules/lodash-es/**/*.js"]
      }
    

    Then I changed my package.json scripts as:

    "test": "env TS_NODE_PROJECT=\"tsconfig.testing.json\" mocha --require ts-node/register 'src/test/**/*.ts'",
    

    Finally I changed the test file like:

    import * as chai from 'chai';
    import 'chai-http';
    import server from '../app';
    
    // Assertions
    chai.should();
    
    chai.use(require('chai-http'));
    

    Well, running the tests works now.

    0 讨论(0)
提交回复
热议问题