【问题标题】:Mocha test. Import class from not exported namespace摩卡测试。从未导出的命名空间导入类
【发布时间】:2018-09-23 22:11:51
【问题描述】:

我需要为我的 Typescript 应用程序编写单元测试。我使用 Mocha 测试框架。 我的网络应用程序中有内部模块(A)和 B 类。

namespace A {
    export class B {
       constructor() {

       }
    } 
}

我需要为 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);
            });

        });
    });

我正在使用命令开始我的测试:

mocha --watch  --recursive  path/Tests

但每次在终端我都会收到错误消息:

ReferenceError: A is not defined

A - 是我的内部模块,我无法导出它。以某种方式,如何测试内部模块的 B 类?

【问题讨论】:

    标签: asp.net unit-testing typescript npm mocha.js


    【解决方案1】:

    在 JavaScript 中无法从本地范围访问变量。基本上这与以下问题相同:

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

    该类需要重构才能访问:

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

    此时namespace在这里没有用处,可以省略,只支持ES模块。

    出于可测试性的原因导出所有内容是一种很好的做法。如果一个类被认为是内部的,它会从定义它的.ts 文件中导出,而不是从index.ts 导出。

    /** @internal */ JSDoc annotation and stripInternal compilation option 可用于从 .d.ts 声明中排除这些导出。它们不会作为常规导入提供,但仍可通过 require 访问。

    【讨论】:

    • 可测试性是重要的关注点,通常应该超过项目管理关注点。我认为导出内部单位没有任何问题,只要它们被认为是内部的。我用@internal 更新了答案。
    猜你喜欢
    • 2015-03-29
    • 2018-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    相关资源
    最近更新 更多