Javascript 如何在子测试中访问Jest测试环境的类属性?
我已经为jest创建了一个测试环境。它的基础非常紧密 我在构造函数中设置了一些值,希望这些值可用于环境中使用的测试。(请参见Javascript 如何在子测试中访问Jest测试环境的类属性?,javascript,jestjs,Javascript,Jestjs,我已经为jest创建了一个测试环境。它的基础非常紧密 我在构造函数中设置了一些值,希望这些值可用于环境中使用的测试。(请参见this.foo=bar) 测试环境: 我使用以下等效工具运行测试: jest --env ./tests/<testing-env>.js 我尝试用es5函数格式替换这两个箭头函数(希望这个在范围内),但没有任何运气 如何从测试环境中的测试中获取类属性?不幸的是,您不能。我建议以与this.global.someGlobalObject=createGlob
this.foo=bar
)
测试环境:
我使用以下等效工具运行测试:
jest --env ./tests/<testing-env>.js
我尝试用es5函数格式替换这两个箭头函数(希望这个
在范围内),但没有任何运气
如何从测试环境中的测试中获取类属性?不幸的是,您不能。我建议以与this.global.someGlobalObject=createGlobalObject()类似的方式公开
foo
并在设置
函数中添加this.global.foo='bar'
。然后,您可以通过调用foo
在测试套件中访问此变量
describe('Sample Test', () => {
it('this.foo = bar', () => {
expect(this.foo).toBe('bar');
});
});
// 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;
//我的自定义环境
const NodeEnvironment=require('jest-environment-node');
类CustomEnvironment扩展了NodeEnvironment{
构造函数(配置,上下文){
超级(配置,上下文);
this.testPath=context.testPath;
}
异步设置(){
等待super.setup();
等待一些setuptasks(this.testPath);
this.global.someGlobalObject=createGlobalObject();
this.global.foo='bar';//{
它('foo=bar',()=>{
expect(foo).toBe('bar');//另一个可能的解决方案是在构造函数中添加一个set函数
setThis(key, val) {
if (process.env.TEST) this[key] = val
}
也许为getThis()构建相同的
不幸的是,你不能。你必须在你的设置函数中将它公开为this.global.foo='bar'
,然后你可以通过调用foo
在你的测试套件中访问它。这不是我希望听到的,但我已经测试并确认这是一个可行的解决方案。如果你想把它作为一个答案来写,我很乐意标记它已被接受。感谢您的帮助!随时!如果您遇到任何问题,请告诉我。绝对不理想,但我感谢您的方法!
// test suite
describe('Sample Test', () => {
it('foo = bar', () => {
expect(foo).toBe('bar'); // <-- foo since it's globally accessible
});
});
setThis(key, val) {
if (process.env.TEST) this[key] = val
}