簡體   English   中英

..._1.default 不是使用 Mocha 測試 TypeScript 時的構造函數

[英]..._1.default is not a constructor when testing TypeScript with Mocha

我正在嘗試使用 mocha 進行單元測試。 我正在使用打字稿,它被編譯成帶有 tsc 的普通 javascript。 我總是收到錯誤:

    src\index.ts:22
        [new FrontendEndpoint(), ...],
         ^
    TypeError: v1_1.default is not a constructor

我采用了兩種方法(並兩次遇到相同的問題):

首先,我創建了一個虛擬測試test.test.ts ,導入我的一些模塊用於測試目的:


    import { APIServer } from './../api/index';
    import { describe } from 'mocha';
    import FrontendEndpoint from '../api/endpoints/frontend/v1';
    import { SocketConnector } from '../api/sockets/socketio';

    describe('TestTest', () => {
        it('should run', (done) => {
            const server = new APIServer(4000, [new FrontendEndpoint()], new SocketConnector([]));
            done();
        });
    });

  1. 使用 ts-mocha

    • 安裝 ts-mocha、mocha、@types/mocha
    • ts-mocha src/test/test.test.ts
  2. 使用 mocha 和編譯的 ts 文件

    • 安裝 mocha, @types/mocha
    • mocha build/test/test.test.js

兩種方式都會產生上述錯誤。

index.ts看起來像這樣:


    import FrontendEndpoint from './api/endpoints/frontend/v1';
    [...]
    new FrontendEndpoint()

編譯(index.js):


    [...]
    const v1_1 = require("./api/endpoints/frontend/v1");
    [...]
    new v1_1.default()

frontend/v1.ts


    export default class FrontendEndpoint {
        [...]
    }

編譯(v1.js):


    class FrontendEndpoint {
        [...]
    }
    exports.default = FrontendEndpoint;

我的 tsconfig 看起來像這樣:

{
    "compilerOptions": {
        "target": "es2015",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "noImplicitReturns": true,
        "noImplicitAny": true,
        "preserveConstEnums": true,
        "strictPropertyInitialization": false,
        "experimentalDecorators": true,
        "typeRoots": [
            "src/types"
        ],
        "emitDecoratorMetadata": true,
        "sourceRoot": "src",
        "outDir": "build"
    },
    "compileOnSave": true,
    "exclude": [
        "node_modules",
        "coverage",
        "build",
        "logs"
    ],
}

似乎只有默認導出有問題。 為什么它們不能按預期工作? 使用node build/index.js運行應用程序時,一切正常,默認導出/導入按預期工作。

在嘗試使用 Webpack、Mocha 和 Jest 向前端 React 應用程序添加單元測試時,我遇到了同樣的問題。 我是否完全錯過了什么?

我自己找到了解決方案。

在調試我的測試時,我發現一些導出沒有被調用。 這是由於文件的循環依賴關系導致它們無法正確導出。

使用https://github.com/pahen/madge找到這些循環並解決它們后,運行測試工作正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM