如何在Jest的自定义测试环境文件中使用TypeScript?

时间:2019-09-30 07:21:06

标签: node.js typescript jestjs

我需要启用一些全局变量以进行测试,因此我要在testEnvironment的{​​{1}}选项中设置一个自定义环境,以实现该目标。

对于我们的项目,我们有一个用于jest.config.json选项的TypeScript文件,该文件工作正常,但是setupFilesAfterEnv似乎仅支持ES5。有没有办法在这种选项中使用TypeScript?

我使用ES5语法成功创建了一个自定义笑话环境,但是由于我们正在注入全局变量,因此我需要TypeScript来声明全局名称空间,请参见:https://stackoverflow.com/a/42304473/4655076

testEnvironment

5 个答案:

答案 0 :(得分:1)

我通过使用 ts-node 和以下命令解决了这个问题:

node -r ts-node/register ./node_modules/jest/bin/jest.js

这实质上是即时编译打字稿,以便 jest 接收发出的 javascript,而无需实际将打字稿源编译为 js。

您需要启用 esModuleInterop TS 编译器选项才能正常工作。

测试环境.ts


import NodeEnvironment from 'jest-environment-node';
import type {Config} from '@jest/types';

class TestEnvironment extends NodeEnvironment {
    
    constructor(config: Config.ProjectConfig) {
        super(config);
        // this.testPath = context.testPath;
        // this.docblockPragmas = context.docblockPragmas;
    }

    public async setup(): Promise<void> {
        await super.setup();

        console.log('SETTING UP...');
        // await someSetupTasks(this.testPath);
        // this.global.someGlobalObject = createGlobalObject();
    
        // // Will trigger if docblock contains @my-custom-pragma my-pragma-value
        // if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') {
        //   // ...
        // }
    }

    public async teardown(): Promise<void> {
        await super.teardown();
        console.log('TEARING DOWN!');
        // this.global.someGlobalObject = destroyGlobalObject();
        // await someTeardownTasks();
        
    }
}

export default TestEnvironment;

但是,此解决方案会破坏 globalSetup -- 如果您使用 jest-ts

答案 1 :(得分:0)

您可能会发现这很有帮助:Configure Jest global tests setup with .ts file (TypeScript)

但是基本上,您只能将已编译的JS文件作为环境传递。

您可以按照该文章的建议进行操作。但这对我不起作用。因此,我手动编译了我的环境。

在package.json中

"test": "tsc --lib es6 --target es6 --skipLibCheck -m commonjs --esModuleInterop true path/to/env.ts && 
jest --config=jest.config.js",

在jest.config.js中

{
  testEnvironment: '<rootDir>/path/to/env.js', // Note JS extension.
}

答案 2 :(得分:0)

您可能知道,打字稿文件只是 javascript 的超集,以提供强类型检查。然而,Jest 的引擎/运行时需要 CommonJS 格式的 JavaScript 文件。

您可以为这个 tsconfig.env.json 设置一个单独的 env.ts。在运行 jest 测试之前编译它并在您的 env.js 中使用编译的 jest.config.js

tsc -p tsconfig.env.json && jest

此外,我从未见过有人在 TS 中编写配置文件。

为什么是 CommonJS?因为 jest 本质上是在节点之上运行的。 node 支持 CommonJS 格式的 Javascript 文件。 Node 最近也开始支持 es 模块了!这是一件大事!

答案 3 :(得分:-1)

您可以在项目的根目录下创建一个global.d.ts文件。

然后,您可以定义全局变量,如下所示。就我而言,它是一个NestJS应用程序,但是您可以定义任何内容。

declare global {
  namespace NodeJS {
    interface Global {
      app: INestApplication;
    }
  }
}

这是客户端项目的另一个示例,其中我们定义了窗口属性,例如innerWidth;

declare namespace NodeJS {
    interface Global {
        innerWidth: number;
        dispatchEvent: Function;
    }
}

答案 4 :(得分:-1)

在您的.d.ts定义文件中:

type MyGlobalFunctionType = (name: string) => void

将成员添加到浏览器的窗口上下文中:

interface Window {
  myGlobalFunction: MyGlobalFunctionType
}

与NodeJS相同:

declare module NodeJS {
  interface Global {
    myGlobalFunction: MyGlobalFunctionType
  }
}

现在您声明根变量

declare const myGlobalFunction: MyGlobalFunctionType;

然后在常规的.ts文件中,但是作为副作用导入,您实际上实现了它:

global/* or window */.myGlobalFunction = function (name: string) {
  console.log("Hey !", name);
};

最后在其他地方使用它:

global/* or window */.myGlobalFunction("Ayush");

myGlobalFunction("Ayush");