【问题标题】:Extending Global in jest with typescript用打字稿开玩笑地扩展全局
【发布时间】:2022-02-11 20:24:56
【问题描述】:

所以我试图在我的测试文件中轻松使用一些全局变量,所以我进行了很多研究并设法制作了一个在我的所有测试文件之前运行的笑话设置文件以初始化全局变量,这就是 @ 987654321@文件

import  app  from'../src/express';
import request from 'supertest';


//Set Express app as global
global.app = request(app);

//TODO: Add global data

它工作正常,但自动完成在我的测试文件中不起作用,所以在搜索问题后我发现我必须将新添加的变量合并到 NodeJS.Global 并最终在一个名为 global.d.ts 的文件中这样做


declare global {
    namespace NodeJS {
     interface Global {
       app: import('supertest').SuperTest<import('supertest').Test>;
     }
   }
 }

但是,尝试其他解决方案仍然没有任何效果。

注意

ts.config

"target": "es2019",
    "moduleResolution": "node",
    "module": "commonjs",
    "lib": ["es2019"],
    "sourceMap": true,
    "outDir": "dist",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "resolveJsonModule": true,
    "alwaysStrict": true,
    "removeComments": true,
    "noImplicitReturns": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "allowJs": true /* Allow javascript files to be compiled. */,
    "typeRoots": [
      "./types",
      "node_modules/@types",
      
    ] /* List of folders to include type definitions from. */,
    "types": [ "node","jest"],
  },
  "include": ["./src/**/*", "./utils/**/*", "localization", "./tests/**/*"],
  "exclude": ["./seeds/**/*"]

jest.config.ts

/*
 * For a detailed explanation regarding each configuration property and type check, visit:
 * https://jestjs.io/docs/configuration
 */

export default {
  clearMocks: true,
  coverageProvider: "v8",
  coverageDirectory: "coverage",
  collectCoverage: true,
  setupFiles: ["<rootDir>/tests/setup.ts"],
  testMatch: [
    "<rootDir>/tests/**/*.test.ts"
  ],

};

【问题讨论】:

    标签: typescript jestjs


    【解决方案1】:

    我有一个类似的用例,我需要一个 safeSubscribe 在我的所有测试中全局可用的助手。
    此函数将执行订阅,然后在一般的 afterEach 挂钩中执行取消订阅,在任何测试后执行。

    我是这样实现的:

    // test/setup/safe-subscribe.ts
    import { Observable, Subscription } from 'rxjs';
    
    const subscriptions: Subscription[] = [];
    const safeSubscribeFn = <T>(source: Observable<T>): T[] => {
      const res: T[] = [];
      const subscription = source.subscribe((value) => {
        res.push(value);
      });
      subscriptions.push(subscription);
      return res;
    };
    
    global.safeSubscribe = safeSubscribeFn; // Add helper implementation
    
    global.afterEach(() => {
      while (subscriptions.length > 0) {
        const subscription = subscriptions.pop();
        subscription?.unsubscribe();
      }
    });
    
    declare global {
      // See: https://stackoverflow.com/a/68328575/12292636
      var safeSubscribe: typeof safeSubscribeFn;
    }
    
    // jest.config.js
    module.exports = {
      ...,
      setupFilesAfterEnv: [
        ...,
        './test/setup/safe-subscribe.ts', // Import your setup in jest config
      ],
    };
    
    // tsconfig.spec.json
    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "outDir": "./out-tsc/spec",
        "module": "commonjs",
        "types": ["jest", "node"],
        "resolveJsonModule": true,
        "esModuleInterop": true,
      },
      "files": ["src/polyfills.ts", "test/setup/*.ts"], // Add it there
      "include": ["src/**/*.d.ts", "src/**/*.spec.ts", "test/setup/*.ts"] // And also there
    }
    

    现在,可以在测试中使用全局定义的safeSubscribe

    // foo.spec.ts
    it('should emit value', () => {
      // Given
      const outputs = safeSubscribe(service.myObservable$); // global import with typescript stuff ✔️
      // When
      actions$.next(action);
      // Then
      expect(outputs).toHaveLength(1);
    });
    

    【讨论】:

      【解决方案2】:

      如果你想像app(而不是global.app)那样使用它,那么全局声明它:

      declare global {
        const app: import('supertest').SuperTest<import('supertest').Test>;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-10-26
        • 2021-01-09
        • 2017-07-11
        • 2018-07-27
        • 2018-12-09
        • 2019-02-06
        • 2017-10-02
        • 1970-01-01
        • 2021-12-09
        相关资源
        最近更新 更多