如何读取测试中的笑话配置值?

ysf*_*ran 13 javascript jestjs

jest允许您使用CLI 选项或文件设置全局配置值package.jsonjest.config.js

您可以在测试中设置一些配置值,例如

jest.setTimeout(10000000)
Run Code Online (Sandbox Code Playgroud)

但我找不到读取配置值的方法,例如

const initialTimeout = jest.testTimeout // this is undefined
jest.setTimeout(10000000)
// do something that takes unusually long time
jest.setTimeout(initialTimeout)
Run Code Online (Sandbox Code Playgroud)

那么如何读取测试中当前设置的全局配置值呢?

小智 -1

您可以在测试中导入 jest.config.js 文件。这是我的 TypeScript 包中的工作代码。

// jest.config.ts
export default {
  preset: 'ts-jest',
  testMatch: [
    '<rootDir>/tst/**/*.ts'
  ],
  transform: {
    '^.+\\.ts?$': 'ts-jest'
  },
  testEnvironment: 'jsdom',
  testURL: 'https://mytest.com',
}

// test.ts
import { default as jestConfig } from '../jest.config';

describe('my test', () => {
  test('get the testURL from jest config.', () => {
    expect(jestConfig.testURL).toBe('https://mytest.com');
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 我想这仅适用于您在该文件中专门定义的配置属性。所以这不是一个理想的解决方案并且容易出错。 (3认同)