【问题标题】:How to access class properties of Jest Test Environment inside child test?如何在子测试中访问 Jest 测试环境的类属性?
【发布时间】:2019-06-29 21:51:31
【问题描述】:

我已经为 jest 创建了一个测试环境。它非常接近于their official docs。

我在构造函数中设置了一些值,我希望这些值可用于环境中使用的测试。 (见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 在范围内)并且没有任何运气。

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

【问题讨论】:

  • 不幸的是,你不能。您必须在您的设置函数中将其公开为this.global.foo = 'bar',然后您可以通过调用foo 在您的测试套件中访问它。
  • 不是我希望听到的,但我已经测试并确认这是一个可行的解决方案。如果您想将其写为答案,我很乐意将其标记为已接受。感谢您的帮助!
  • 随时!如果您遇到任何问题,请告诉我。

标签: javascript jestjs


【解决方案1】:

很遗憾,你不能。我建议以与this.global.someGlobalObject = createGlobalObject(); 类似的方式公开foo,并在setup 函数中添加this.global.foo = 'bar'。然后,您可以通过调用 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 
  });
});

【讨论】:

  • 绝对不理想,但我很欣赏这个方法!
【解决方案2】:

另一个可能的解决方案是在你的构造函数中添加一个 set 函数。

setThis(key, val) {
   if (process.env.TEST) this[key] = val
}

也许为 getThis() 构建相同的代码

【讨论】:

    猜你喜欢
    • 2023-02-19
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 2022-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    相关资源
    最近更新 更多