摩卡咖啡测试.从未导出的名称空间导入类 [英] Mocha test. Import class from not exported namespace

查看:66
本文介绍了摩卡咖啡测试.从未导出的名称空间导入类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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() {

       }
    } 
}

我需要为B类编写一些单元测试.

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-是我的内部模块,我无法导出它.以某种方式,如何测试内部模块的B类?

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?

推荐答案

在JavaScript中无法从本地作用域访问变量.基本上,这与以下问题相同:

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() {

       }
    } 
}

此时namespace在这里没有用,只能在ES模块中忽略它.

At this point namespace is of no use here, it can be omitted in favour of ES modules only.

出于可测试性的原因,导出所有内容是一个好习惯.如果某个类被认为是内部类,则将从定义该类的.ts文件中导出,而不是从index.ts中导出.

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注释和stripInternal编译选项可用于从.d.ts声明中排除这些导出.它们将不能作为常规进口产品使用,但仍可以通过require到达.

/** @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.

这篇关于摩卡咖啡测试.从未导出的名称空间导入类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆