简体   繁体   中英

Karma - TypeScript - Can't find variable: exports

I am learning to write Unit Test cases for an angular project written in Typescript . I have chosen Karma and Mocha for that. Here is the application structure:

Project/
├── app/
│   └── components/
│       └── mycoolcomponent/
│           ├── coolcomp.spec.ts
│           └── coolcomp.ts
│   
├── node_modules/
│
├── gulpfile.js
│── karma.conf.js
│── package.json 
└── tsconfig.json  

Here is the karma.conf.js :

module.exports = function (config) {
    config.set({        
        basePath: '',
        frameworks: ['mocha', 'chai', 'sinon'],

        files: [
            'app/components/mycoolcomponent/coolcomp.ts',
            'app/components/mycoolcomponent/coolcomp.spec.ts'
        ],

        exclude: [
        ],

        preprocessors: {
            '**/*.ts': ['typescript']
        },

        typescriptPreprocessor: {
            options: {
                sourceMap: true, // generate source maps
                noResolve: false // enforce type resolution
            },
            transformPath: function (path) {
                return path.replace(/\.ts$/, '.js');
            }
        },       

        reporters: ['progress'],        
        port: 9876,        
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,        
        browsers: ['Chrome', 'IE', 'PhantomJS'],
        singleRun: true,
        concurrency: Infinity
    })
}  

tsconfig.json :

{
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "system",
    "moduleResolution": "node",
    "noImplicitAny": false,
    "outDir": "Scripts/app",
    "removeComments": false,
    "sourceMap": true,
    "target": "es6",
    "inlineSources": true
  },
  "exclude": [
    "node_modules",
    "wwwroot",
    "typings/boot",
    "typings/boot.d.ts"
  ]
}

Gulp task :

gulp.task('test', function (done) {
    new Server({
        configFile: __dirname + '/karma.conf.js',
        singleRun: true
    }, done).start();
});  

Package.json has the following dev-dependencies:

 "devDependencies": {
    "@types/chai": "^4.0.1",
    "@types/expect": "^1.20.1",
    "@types/mocha": "^2.2.41",
    "@types/sinon": "^2.3.3",
    "chai": "^4.1.0",
    "del": "2.2.2",
    "gridstack": "^0.3.0",
    "gulp": "^3.9.1",
    "gulp-sourcemaps": "2.4.1",
    "gulp-typescript": "3.1.7",
    "karma": "^1.7.0",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-ie-launcher": "^1.0.0",
    "karma-mocha": "^1.3.0",
    "karma-phantomjs-launcher": "^1.0.4",
    "karma-sinon": "^1.0.5",
    "karma-typescript-preprocessor": "^0.3.1",
    "merge": "1.2.0",
    "mocha": "^3.4.2",
    "phantomjs": "^2.1.7",
    "sinon": "^2.4.1",
    "typescript": "^2.4.2",
    "typings": "2.1.0"
  }

coolcomp.ts :

export class Calculator {
    add(x: number, y: number): number {
        return x + y;
    }        
}

coolcomp.spec.ts :

import { Calculator } from "./coolcomp";    
var expect = chai.expect;

describe("Calculator Mocha", () => {
    var calculator;
    beforeEach(() => {
        calculator = new Calculator();
    });

    xit("can add", () => {
        var result = calculator.add(5, 5);
        expect(result).to.be.equal(1);    
    });
});  

When I run the gulp task I am getting this error:

ReferenceError: Can't find variable: exports

However if I remove the export keyword from coolcomp.ts and the 1st line (import..) from coolcomp.spec.ts the tests run smoothly. There are already few questions like this posted here on SO but none helped me.
Can someone please guide me where I am doing it wrong?

UPDATE : With the help from StackOverflow community and few other forums I have figured out the solution to this problem. For those who wish to see it here is the url of my code's repository: GitHub Link

Here it goes your solution. Remove sinon for a while.

npm uninstall @types/sinon npm uninstall sinon

Test if tsc works from the command line. Then execute: "karma start" from the command line. No need gulp.

    // Karma configuration
    module.exports = function (config) {
        config.set({
            basePath: "",
            frameworks: [ "karma-typescript" , "mocha", "chai" ],
            files: [
                { pattern: "app/components/mycoolcomponent/**/*.ts", included: true, watches: false  }
            ],
            preprocessors: { "app/components/mycoolcomponent/**/*.ts": ["karma-typescript"] },
            port: 8081,
            typescriptPreprocessor: {
                options: {
                    sourceMap: true,
                    noResolve: false
                },
                transformPath: function(path) {
                    return path.replace(/\.ts$/, ".js");
                }
            },
            browsers: [ "Chrome" ],
            reporters: [ "progress", "mocha", "karma-typescript" ],
            autoWatch: true,
            singleRun: false,
            concurrency: Infinity,
            plugins: [
                require("karma-typescript"),
                require("karma-chrome-launcher"),
                require("karma-sourcemap-writer"),
                require("karma-mocha-reporter"),
                require("karma-mocha"),
                require("karma-chai")
            ]
        })
    }

// TSCONFIG

{
"compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "noEmitOnError": false,
    "noImplicitAny": false,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "allowJs": true,
    "removeComments": true,
    "inlineSourceMap": true
},
"types": [
  "node",
  "mocha",
  "chai",
  "expect"
],
"version": "2.4.1",
"include": [
    "app/**/*.ts"
]

}

// PACKAGE.JSON

{
  "name": "unittestingwithkarmamocha",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/chai": "^4.0.1",
    "@types/expect": "^1.20.1",
    "@types/mocha": "^2.2.41",
    "chai": "^4.1.0",
    "gulp": "^3.9.1",
    "karma": "^1.7.0",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-coverage": "^1.1.1",
    "karma-ie-launcher": "^1.0.0",
    "karma-mocha": "^1.3.0",
    "karma-mocha-reporter": "^2.2.3",
    "karma-sinon": "^1.0.5",
    "karma-source-map-support": "^1.2.0",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-sourcemap-writer": "^0.1.2",
    "karma-typescript": "^3.0.4",
    "karma-typescript-preprocessor": "^0.3.1",
    "mocha": "^3.4.2",
    "phantomjs": "^2.1.7",
    "systemjs": "^0.20.17",
    "typescript": "^2.4.2"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM