unit-testing - 获取 TypeScript 类的实例?

标签 unit-testing typescript

我有一些遗留代码想要开始单元测试。这是一个像这样的类:

export class Controller {
    private something: any;

    constructor() { this.something = true; }

    public getSomething(): any { return this.something; }
}

尝试使用 Mocha 对其进行单元测试,如下所示:

import Controller from '../../src/Controller';

describe('Controller', () => {
    let subject: any;

    beforeEach( () => {
        subject = new Controller(); // compiler complains here
    });

    describe('getOptions()', () => {
        it('should get something', () => {
            let result: any = subject.getOptions();
            if (typeof result !== 'object') {
                throw new Error('Expected object but got ' + result);
            }
        });
    });
});

编译器提示:

[ts] Cannot use 'new' with an expression whose type lacks a call or construct signature.

如何获取 Controller 类的实例来运行测试?

最佳答案

它不起作用,因为您试图将 Controller 导入为默认导出,但它却没有。

尝试:

import {Controller} from '../../src/Controller';

或者:

export default class Controller {

您可以在 MDN 页面 here 上阅读有关导入的更多信息。 .

关于unit-testing - 获取 TypeScript 类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41020998/

相关文章:

类型上不存在 Angular2 属性

angular - 如何应用文本装饰:line thorough on clicking a checkbox in angular

javascript - 为 Azure API 管理创建的 SAS token 无效

C++ 单元测试框架

c# - 模拟 Controller 以测试区域内的 ViewEngine - nullreference 和 RouteData

typescript - 如何让 TypeScript 知道自定义 Jest 匹配器?

typescript - 如何让 CDK 只创建一个弹性 IP 地址以用于单个 EC2 实例 (AWS CDK)

python - "Zero Iteration"- 简单联系表功能中的端到端验收测试

c# - 单元测试预期在 MSTest 上调用异步操作时抛出异常

python - 在 python unittest 中关闭一些打印