簡體   English   中英

如何使用 TypeScript 運行我的摩卡裝置?

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

使用 ExpressJS、TypeScript 和 Mocha,我希望能夠在每次測試后關閉我的服務器連接。

我知道我可以在每個測試文件上做這樣的事情

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

但這會導致我的代碼重復很多,我想做得更干凈一點,所以我閱讀了 Mocha 文檔並找到了有關全局固定裝置的信息。 我使用以下語法創建了一個名為“fixtures.ts”的文件:

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

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

使用它,我希望能夠在測試結束后關閉我的服務器。 我的問題是 fixtures.ts 在運行我的測試時根本沒有做任何事情。 我在 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"
  },

在 mocha 文檔中,全局夾具使用的文件擴展名類似於“mjs”或“cjs”,這在使用 TypeScript 時會不會有問題?

最后,這只是我的 package.json 的錯字問題。 我最終在文件名后使用 --require 修復了它。 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