在 BeforeEach 中设置 this.variable 时,无法设置未定义的属性“变量”

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

我错过了什么吗?


牛魔王的故事
浏览 189回答 2
2回答

哔哔one

最简单的方法是删除使用this并在describe()回调范围内声明一个变量:  describe('tests', () => {    let dom;    beforeEach(async () =>      Promise.resolve('foo').then(result => {        dom = result;      })    );    it('works', () => {      console.log(dom); // => foo    });  });

繁星coding

您在承诺和测试回调函数中使用箭头函数。thenit在箭头函数之前,每个新函数都根据函数的调用方式定义了自己的 this 值:在构造函数的情况下是一个新对象。在严格模式函数调用中未定义。如果函数被称为“对象方法”,则为基础对象。所以你的代码的问题是在测试的回调箭头函数this的范围内是指describe块的父范围。箭头函数没有自己的this. 使用封闭词法范围的 this 值;箭头函数遵循正常的变量查找规则。因此,在搜索当前范围内不存在的 this 时,箭头函数最终会从其封闭范围中找到 this。作为一种选择,您可以在块的父范围内定义变量并在回调describe中使用它。beforeAllit
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript