【问题标题】:TypeError: Cannot set property 'variable' of undefined, when setting this.variable in BeforeEach类型错误:在 BeforeEach 中设置 this.variable 时,无法设置未定义的属性“变量”
【发布时间】:2020-03-31 13:47:19
【问题描述】:

我是 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

我错过了什么吗?

【问题讨论】:

  • 为什么不做let output; beforeEach( (done) => Promise...then( (result) => output = result; ) ) 然后检查output 的有效性

标签: javascript unit-testing mocha.js


【解决方案1】:

最简单的方法是去掉this的使用,在describe()回调的范围内声明一个变量:

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

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

【讨论】:

    【解决方案2】:

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

    在箭头函数之前,每个新函数都定义了自己的 this 值 基于函数的调用方式:

    • 构造函数中的新对象。
    • 在严格模式函数调用中未定义。
    • 如果函数被称为“对象方法”,则为基础对象。

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

    箭头函数没有自己的this。的这个值 使用封闭词法范围;箭头功能遵循正常 变量查找规则。所以在搜索这个不是 存在于当前范围内,箭头函数最终会找到 this 从它的封闭范围。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2021-11-09
      • 2012-01-18
      • 1970-01-01
      相关资源
      最近更新 更多