【问题标题】:How to resolve Class is not a constructor error in Typescript Mocha Testing?如何解决 Typescript Mocha 测试中的 Class is not a constructor 错误?
【发布时间】:2020-07-31 13:23:20
【问题描述】:

我有以下课程:

import http, { RequestListener } from 'http';
import { Application } from './application';

export class WebServer {

  private httpServer: http.Server;
  private requestListener: RequestListener;

  public async start(application: Application, port: number) {
    this.requestListener = application.getRequestListener();
    this.httpServer = http.createServer(this.requestListener);
    await this.httpServer.listen(port);
  }

  public async stop() {
    await this.httpServer.close();
  }

  public getHttpServer(): http.Server {
    return this.httpServer;
  }

  public getRequestListener(): RequestListener {
    return this.requestListener;
  }
}

我有以下简单的测试用例:

import { expect } from 'chai';
import 'mocha';
import { Application } from './../infrastructure';
import { WebServer } from './../infrastructure';

describe('WebServer Tests', () => {
    const webServer = new WebServer();
    const webServerProto = Object.getPrototypeOf(webServer)
    it('Checking WebServer Initialization', () => {
        expect(webServerProto).to.not.be.null;
        expect(webServerProto.httpServer).to.not.be.null;
        expect(webServerProto.requestListener).to.not.be.null;
    });

我在运行测试时遇到导入错误。即,我得到以下信息:

TypeError:"uncaughtException": WebServer is not a constructor

这让我相信我的测试文件中的导入有问题。作为参考,这是我的启动脚本和测试脚本:

"start": "node --inspect=5858 -r ts-node/register ./src/index.ts"
    "test": "cross-env TS_NODE_FILES=true mocha --exit --require ts-node/register --watch-extensions ts --colors ./src/test/*-tests.ts",

有人知道我需要对我的测试环境做什么才能访问 WebServer 类吗? npm start 工作得很好。运行 npm test 时出现构造函数错误。任何建议将不胜感激!

【问题讨论】:

  • 你能有一些循环依赖,例如。在调用 new 之前尝试 console.log(WebServer)..

标签: javascript typescript mocha.js chai


【解决方案1】:

为类 WebServer 添加一个构造函数

import http, { RequestListener } from 'http';
import { Application } from './application';

export class WebServer {

  constructor(){}
  private httpServer: http.Server;
  private requestListener: RequestListener;

  public async start(application: Application, port: number) {
    this.requestListener = application.getRequestListener();
    this.httpServer = http.createServer(this.requestListener);
    await this.httpServer.listen(port);
  }

  public async stop() {
    await this.httpServer.close();
  }

  public getHttpServer(): http.Server {
    return this.httpServer;
  }

  public getRequestListener(): RequestListener {
    return this.requestListener;
  }
}

另外,您的导入路径看起来很奇怪。

我早就料到了

import { WebServer } from './../infrastructure/WebServer';
import { Application } from './../infrastructure/Application';

【讨论】:

    猜你喜欢
    • 2020-11-13
    • 1970-01-01
    • 2013-01-28
    • 2021-10-20
    • 2021-12-23
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 2019-10-25
    相关资源
    最近更新 更多