简体   繁体   English

如何使用 TypeScript 运行我的摩卡装置?

[英]How to run my fixtures for mocha using TypeScript?

Using ExpressJS, TypeScript and Mocha, I want to be able to close my server connection after each test.使用 ExpressJS、TypeScript 和 Mocha,我希望能够在每次测试后关闭我的服务器连接。

I'm aware that I can do something like this on each test file我知道我可以在每个测试文件上做这样的事情

    this.afterAll(function () {
        server.close();
    });

But this will cause a lot of repetition on my code and I want to do it a little bit more cleaner, so I was reading the Mocha documentation and found about the global fixtures.但这会导致我的代码重复很多,我想做得更干净一点,所以我阅读了 Mocha 文档并找到了有关全局固定装置的信息。 I created a file called 'fixtures.ts' with the following syntax:我使用以下语法创建了一个名为“fixtures.ts”的文件:

import { app, server } from '../../../app';

export const mochaHooks = (): Mocha.RootHookObject => {
    return {
        afterAll(done: Mocha.Done) {
            console.log('Closing server');
            server.close();
            done();
        },
    };
};

Using this, I want to be able to close my server after the tests end.使用它,我希望能够在测试结束后关闭我的服务器。 My problem here is that fixtures.ts isn't doing anything at all when running my tests.我的问题是 fixtures.ts 在运行我的测试时根本没有做任何事情。 My syntax on package.json is something like:我在 package.json 上的语法是这样的:

  "scripts": {
    "build": "npx tsc",
    "start": "node build/app.js",
    "dev": "concurrently \"npx tsc --watch\" \"nodemon -q build/app.js\"",
    "test": "mocha --require ts-node/register 'test/{controllers,services}/*.ts' 'test/utils/server/fixtures.ts'",
    "preseed": "npm run build",
    "seed": "node build/test/utils/seeders/seeds.js"
  },

In the mocha documentation, the file extension that the global fixture uses is something like 'mjs' or 'cjs', could this be a problem when using TypeScript?在 mocha 文档中,全局夹具使用的文件扩展名类似于“mjs”或“cjs”,这在使用 TypeScript 时会不会有问题?

At the end it was just a typo problem on my package.json.最后,这只是我的 package.json 的错字问题。 I ended up fixing it using --require after the file name.我最终在文件名后使用 --require 修复了它。 ts-node does the job for using the global fixture. ts-node 完成使用全局夹具的工作。

  "scripts": {
    "build": "npx tsc",
    "start": "node build/app.js",
    "dev": "concurrently \"npx tsc --watch\" \"nodemon -q build/app.js\"",
    "test": "mocha --require ts-node/register --require 'test/utils/server/fixtures.ts' 'test/{controllers,services}/*.ts' ",
    "seed": "node --require ts-node/register test/utils/seeders/seeds.ts"
  },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM