如何在子测试中访问 Jest 测试环境的类属性?

2023-12-24

我已经为jest创建了一个测试环境。它非常接近于他们的官方文档 https://jestjs.io/docs/en/configuration#testenvironment-string.

我在构造函数中设置了一些值,我希望将它们提供给环境中使用的测试。 (看this.foo = bar).

测试环境:

// my-custom-environment
const NodeEnvironment = require('jest-environment-node');

class CustomEnvironment extends NodeEnvironment {
  constructor(config, context) {
    super(config, context);
    this.testPath = context.testPath;
    this.foo = 'bar'; // Trying to access
  }

  async setup() {
    await super.setup();
    await someSetupTasks(this.testPath);
    this.global.someGlobalObject = createGlobalObject();
  }

  async teardown() {
    this.global.someGlobalObject = destroyGlobalObject();
    await someTeardownTasks();
    await super.teardown();
  }

  runScript(script) {
    return super.runScript(script);
  }
}

module.exports = CustomEnvironment;

我使用以下等效项运行测试:

jest --env ./tests/<testing-env>.js

我在哪里访问this.foo在我的测试中,在这个测试环境中进行测试?

describe('Sample Test', () => {
  it('this.foo = bar', () => {
    expect(this.foo).toBe('bar');
  });
});

我尝试用 es5 函数格式替换两个箭头函数(希望this将在范围内)并且没有任何运气。

如何从测试环境中的测试中获取类属性?


不幸的是,你不能。我建议暴露foo以类似的方式this.global.someGlobalObject = createGlobalObject();并添加this.global.foo = 'bar'setup功能。然后,您可以通过调用在测试套件中访问此变量foo.

// my-custom-environment
const NodeEnvironment = require('jest-environment-node');

class CustomEnvironment extends NodeEnvironment {
  constructor(config, context) {
    super(config, context);
    this.testPath = context.testPath;
  }

  async setup() {
    await super.setup();
    await someSetupTasks(this.testPath);
    this.global.someGlobalObject = createGlobalObject();
    this.global.foo = 'bar'; // <-- will make foo global in your tests
  }

  async teardown() {
    this.global.someGlobalObject = destroyGlobalObject();
    await someTeardownTasks();
    await super.teardown();
  }

  runScript(script) {
    return super.runScript(script);
  }
}

module.exports = CustomEnvironment;

然后在您的测试套件中:

// test suite
describe('Sample Test', () => {
  it('foo = bar', () => {
    expect(foo).toBe('bar'); // <-- foo since it's globally accessible 
  });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在子测试中访问 Jest 测试环境的类属性? 的相关文章

随机推荐