Currently, I am in the process of mastering how to write Unit Test cases for an angular project coded in Typescript
. To facilitate this, I have opted for utilizing Karma
and Mocha
. Below lays out the structure of the application:
Project/
├── app/
│ └── components/
│ └── mycoolcomponent/
│ ├── coolcomp.spec.ts
│ └── coolcomp.ts
│
├── node_modules/
│
├── gulpfile.js
│── karma.conf.js
│── package.json
└── tsconfig.json
Displayed is the configuration file for 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,
noResolve: false
},
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
})
}
The definition within 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"
]
}
Detailed Gulp task:
gulp.task('test', function (done) {
new Server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start();
});
Included within Package.json are these dev-dependencies:
"devDependencies": {
"@types/chai": "^4.0.1",
// Other dependencies listed here
}
Inside coolcomp.ts :
export class Calculator {
add(x: number, y: number): number {
return x + y;
}
}
This is what's found in 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);
});
});
Upon initiating the gulp task, an error surfaces:
ReferenceError: Can't find variable: exports
Interestingly, by removing the export
keyword from coolcomp.ts and the import line from coolcomp.spec.ts, the tests operate without a hitch. Despite previous questions on similar topics on StackOverflow, none were applicable or rendered the needed guidance.
Could someone kindly direct me towards identifying where the issue lies?
UPDATE: After receiving support from both StackOverflow and other forums, I've uncovered the solution to the current problem. For those interested in viewing it, follow this link to access the code repository: GitHub Link