【发布时间】: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