我正在尝试在Jest的beforeEach
中实例化两个类。由于某些原因,其余两个函数似乎无法访问这两个变量。是关闭问题吗?
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);
});
});
答案 0 :(得分:1)
Client1
和Client2
仅在beforeEach范围内可见。将变量移到实例变量和测试的“全局”范围内,它应该可以工作。
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);
});
});
使用一些范围信息进行编辑。
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"
}