![](/img/trans.png)
[英]How to make sure 'this' inside mocha test have access to class properties
[英]How to access class properties of Jest Test Environment inside child test?
我为jest创建了一个测试环境。 它非常接近于 他们的官方文档。
我在构造函数中设置了一些值,我希望这些值可用于环境中使用的测试。 (见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.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
});
});
另一个潜在的解决方案是向构造函数添加一个 set 函数。
setThis(key, val) {
if (process.env.TEST) this[key] = val
}
也许为getThis()
构建相同的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.