Reputation: 96454
My example has
let resort30 = new Resort('Alta');
at the top of the file and then uses it within the the test case, i.e.
let alta = new Visit(resort30, '03/01/2000'); // Note this is before any describe
That works. However if I create a before
or beforeEach
within the describe
and before all the it
s with:
before(function () {
let resort30 = new Resort('Alta');
});
and comment out the original declaration, then resort30
isn't recognized with
ReferenceError: resort30 is not defined
at Context.<anonymous> (test/ski_resorts_using_befores.spec.js:52:26)
How can I get it to work when I move that variable into the before
or beforeEach
so all it
s can use it ?
I don't want it at the top, I want it to be scoped to the describe as I plan more describes in this file. Even with 1 describe , I want to be able to use before
and beforeEach` for variables and objects i wanna create.
Upvotes: 8
Views: 4407
Reputation: 8515
let
is visible only in the scope it has been declared or from inner scopes. That's why it's not recognized in another scope. To have some kind of a global variable but scoped to the describe()
block you need to declare it at the top of the block and initialize in the before()
or beforeEach()
block:
describe('Test suite', () => {
let resort30 = null;
before(() => {
resort30 = new Resort('Alta');
});
it('should pass', () => {
console.log(resort30);
});
});
Upvotes: 8
Reputation: 119
You aren't able to see resort30 because if you declare it inside a function, it's scoped only to that function.
let resort30; // declare it at the top level scope of the file
before(function () {
resort30 = new Resort('Alta'); // modify the value here
});
Upvotes: 3