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

Viewed 380

I'm new to Javascript. I have the following code following exactly per https://stackoverflow.com/a/58785118

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

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

When running the test, it complaints

1) tests
       "before each" hook for "works":
     TypeError: Cannot set property 'dom' of undefined

Did I miss anything?

2 Answers

The easiest way is to remove the usage of this and declare a variable in the scope of the describe() callback:

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

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

You use arrow function in your promise then and in test it callback functions.

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".

So the problem with your code is that in scope of test's callback arrow function this is refers to parent scope of describe block.

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.

As one option you can define variable at parent scope at describe block and use it in beforeAll and it callback.

Related