Mocha test. Import class from not exported namespa

2019-08-23 12:21发布

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?

1条回答
我只想做你的唯一
2楼-- · 2019-08-23 12:44

There is no way to reach variables from local scopes in JavaScript. Basically this is same problem as:

(() => {
  let bar = 1;
})();
// bar cannot be reached from this scope

The class needs to be refactored to be reachable:

export namespace A {
    export class B {
       constructor() {

       }
    } 
}

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 from index.ts.

/** @internal */ JSDoc annotation and stripInternal 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 with require.

查看更多
登录 后发表回答