I need to write unit test for my Typescript app. I use Mocha test framework. I have got internal module(A) in my web app and class B there.
namespace A {
export class B {
constructor() {
}
}
}
I need to write some unit test for class B.
/// <reference path="path/A.ts" />
import { expect } from 'chai';
describe('B test', function () {
describe('#constructor()', () => {
it('Should create B with default data', () => {
let b = new A.B();
expect(b.age).to.equal(90);
});
});
});
I'm starting my tests with command:
mocha --watch --recursive path/Tests
But every time in terminal I receive error message:
ReferenceError: A is not defined
A - is my internal module and I can't to export it. Is it some way, how is it possible to test internal module's class B?
There is no way to reach variables from local scopes in JavaScript. Basically this is same problem as:
The class needs to be refactored to be reachable:
At this point
namespace
is of no use here, it can be omitted in favour of ES modules only.It is a good practice to export everything for testability reasons. If a class is considered internal, it's exported from
.ts
file where it was defined but not fromindex.ts
./** @internal */
JSDoc annotation andstripInternal
compilation option can be used to exclude these exports from .d.ts declarations. They won't be available as regular imports but will still be reachable withrequire
.