javascript - BeforeEach 中的 Jest 闭包
问题描述
我正在尝试beforeEach
在 Jest 中实例化两个类。出于某种原因,其余函数似乎无法访问这两个变量。是关闭问题吗?
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);
});
});
解决方案
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"
}
推荐阅读
- c# - 在不同的列上使用 LINQ 连接三个表并在最后打印总和
- python - 在 python 中有多个循环会提高脚本效率吗?
- c# - WebView2 MouseEnter 事件处理程序永远不会触发
- progressive-web-apps - Omnifaces ViewScoped 与 PWAResourceHandler
- string - 如何通过字符串格式的日期比较在 MongoDB 集合中查找文档
- azure - 使用 Azure 数据工厂生成受密码保护的 CSV 文件
- haskell - Haskell,如何在不遇到错误的情况下返回列表
- docusignapi - Docusign - 生成用于获取 Auth 令牌的授权代码
- awk - 为什么 awk 不将变量写入 csv 文件?
- python - 覆盖位于 django MEDIA_ROOT 之外的图像