首页 > 解决方案 > 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);
    });



});

标签: javascriptjestjs

解决方案


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

您可以尝试将其可视化为分支结构或框内框: 分支可视化

方形可视化


推荐阅读