要求在测试文件中导出默认模块

Require export default module in test files

我试图在我的测试文件中要求一个模块,但是当我将它作为默认模块导出时我不知道如何去做。我有以下代码:

server.ts

import { MyClass } from './myClass';

/* Other code here */

const server = app.listen(port, () => {
    console.log('Started');
});

export default server;

这使用 webpack 构建得非常好。我导出服务器是因为我希望能够在我的规范文件中对其进行测试。我尝试在我的测试文件中这样做(使用 mocha):

testFile.ts

describe('Express Server', () => {
    let server: any;

    beforeEach(() => {
        delete require.cache[require.resolve('./server.ts')];
        server = require('./server.ts');
    });

    afterEach((done: any) => {
        server.close(done);
    });

    it('sample test', (done: any) => {
        done();
    });
});

当然,以上并没有测试什么。但这并不重要,因为它会在每个之前抛出错误:SyntaxError: Unexpected token {

如何要求我的服务器模块?我需要能够在每次测试前重置要求。

您的测试环境似乎不支持 TypeScript 文件。

尝试使用 ts-node 运行 mocha 命令

mocha -r ts-node/register src/**/test.ts

来源:https://journal.artfuldev.com/write-tests-for-typescript-projects-with-mocha-and-chai-in-typescript-86e053bdb2b6

所以我不得不更改 tsconfig.json 中定义的模块。我将其从 "es2015" 更改为 "commonjs" 并且问题中发布的错误消失了。此外,我还必须更改我检索服务器的方式,如下所示(在 require 之后添加 .default)。

tsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./",
        "outDir": "./dist",
        "target": "es5",
        "module": "commonjs", // Had to change the value for this
        "sourceMap": true
    },
    "include": [
        "./src/**/*"
    ],
    "exclude": [
        "./dist",
        "./node_modules"
    ]
}

testFile.ts

describe('Express Server', () => {
    let server: any;

    beforeEach(() => {
        delete require.cache[require.resolve('./server.ts')];

        // Had to change this line to have ".default" at the end
        server = require('./server.ts').default;
    });

    afterEach((done: any) => {
        server.close(done);
    });

    it('sample test', (done: any) => {
        done();
    });
});

我没有完全了解 "es2015" 和 "commonjs" 之间的区别,所以如果有人知道,请分享。使用以上更改,我能够 运行 以下命令:

nyc ts-mocha -p tsconfig.json --reporter mocha-multi-reporters --reporter-options configFile=test/config/mocha-config.json test/**/*.test.ts --exit

它拉入了服务器,我的所有测试都通过了,没有任何错误。谢谢 Freez 提到测试环境可能无法正确读取打字稿。