TypeError: Cannot set property 'variable' of undefined, when setting this.variable in BeforeEach

TypeError: Cannot set property 'variable' of undefined, when setting this.variable in BeforeEach

我是 Javascript 的新手。我有以下代码完全遵循

  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

我错过了什么吗?

最简单的方法是删除 this 的用法并在 describe() 回调的范围内声明一个变量:

  describe('tests', () => {
    let dom;
    beforeEach(async () =>
      Promise.resolve('foo').then(result => {
        dom = result;
      })
    );

    it('works', () => {
      console.log(dom); // => foo
    });
  });

您在承诺 then 和测试 it 回调函数中使用了 arrow function

Before arrow functions, every new function defined its own this value based on how the function was called:

  • A new object in the case of a constructor.
  • undefined in strict mode function calls.
  • The base object if the function was called as an "object method".

所以你的代码的问题是在测试的回调箭头函数范围内 this 是指 describe 块的父范围。

An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this which is not present in current scope, an arrow function ends up finding the this from its enclosing scope.

作为一种选择,您可以在 describe 块的父作用域定义变量,并在 beforeAllit 回调中使用它。