我是 Javascript 的新手。我有以下代码完全按照https://stackoverflow.com/a/58785118 describe('tests', () => { beforeEach(async () => Promise.resolve('foo').then(result => { this.dom = result; }) ); it('works', () => { console.log(this.dom); // => foo }); });运行测试时,它抱怨1) tests "before each" hook for "works": TypeError: Cannot set property 'dom' of undefined我错过了什么吗?
2 回答

哔哔one
TA贡献1854条经验 获得超8个赞
最简单的方法是删除使用this并在describe()回调范围内声明一个变量:
describe('tests', () => {
let dom;
beforeEach(async () =>
Promise.resolve('foo').then(result => {
dom = result;
})
);
it('works', () => {
console.log(dom); // => foo
});
});

繁星coding
TA贡献1797条经验 获得超4个赞
您在承诺和测试回调函数中使用箭头函数。then
it
在箭头函数之前,每个新函数都根据函数的调用方式定义了自己的 this 值:
在构造函数的情况下是一个新对象。
在严格模式函数调用中未定义。
如果函数被称为“对象方法”,则为基础对象。
所以你的代码的问题是在测试的回调箭头函数this
的范围内是指describe
块的父范围。
箭头函数没有自己的
this
. 使用封闭词法范围的 this 值;箭头函数遵循正常的变量查找规则。因此,在搜索当前范围内不存在的 this 时,箭头函数最终会从其封闭范围中找到 this。
作为一种选择,您可以在块的父范围内定义变量并在回调describe
中使用它。beforeAll
it
添加回答
举报
0/150
提交
取消