Reputation: 77
I´m trying to instantiate two classes in a beforeEach
in Jest. For some reason, these two variables seem to be inaccessible for the rest of the functions. Is it a closure problem?
describe('Restaurant', () => {
let instance: Restaurant;
beforeEach(() => {
instance = new Restaurant();
const Client1 = new User(Client1)
const Client2 = new User(Client2);
});
it('serve two clients', () => {
Here Client1 and Client2 are not accesible
expect(() => instance.serve(Client1, Client2)).toEqual(1);
});
});
Upvotes: 1
Views: 1448
Reputation: 939
Client1
and Client2
are only visible in the scope of beforeEach. Move your variables up to the instance variable, and "global" scope of the test, and it should work.
describe('Restaurant', () => {
let instance: Restaurant;
let Client1 = null;
let Client2 = null;
beforeEach(() => {
instance = new Restaurant();
Client1 = new User(Client1)
Client2 = new User(Client2);
});
it('serve two clients', () => {
Here Client1 and Client2 are not accesible
expect(() => instance.serve(Client1, Client2)).toEqual(1);
});
});
Edit with a little scope information.
class WorkWithPeople {
let person = new person();
//Here we have a function scope or local scope. It has acces to the parent scope where "person" is defined (much like your instance).
ClonePerson = (person) => {
//This is a local scope variable - the clone. The "clone" is only available within the scope of ClonePerson
let clone = this.person;
}
SetAgeForPerson = () => {
this.person.age = 25; // We can do this because "person" is defined in the parent scope of SetAgeForPerson.
clone.age = 25; // We cannot do this, because clone is defined in the scope of "ClonePerson", a sibling scope to SetAgeForPerson.
}
ClonePersonAndSetAge = () => {
let clone = this.person;
//This scope is defined as a child scope of "ClonePersonAndSetAge" - so it has access to all the parents scopes
let ChildSopeSetAge = () => {
clone.age = 25;
this.person.name = "Jack Overflow"; // We can do this because person is available in a parent scope.
}
}
//Most important to notice is that ALL scopes defined in a sibling are "invisible"
}
You can try and visualize it either a as a branching structure, or boxes within boxes:
Upvotes: 1