Home > Enterprise >  While testing in javascript, Variables defined in 'before' block is showing undefined whil
While testing in javascript, Variables defined in 'before' block is showing undefined whil

Time:04-08

This is a sample test where I am testing that testNum should be 0,

code:

describe("Test Contract", () => {
    
    before(async () => {
        const testNum = 0;
    })
    
    it("should be zero", function () {
        expect(testNum).to.equal(0);
    })
  }

But I am getting an error saying testNum is undefined.

Error:

1) Test Contract
       should be zero:
     ReferenceError: testNum is not defined

What I am doing wrong?

CodePudding user response:

Variable testNum is scoped to the {} where you defined it. Also, const is used for read only values. I assume you want to reassign testNum multiple times. Therefore you should use let.

What you probably want is:

describe("Test Contract", () => {
    let testNum;
    before(async () => {
        testNum = 0;
    })
    
    it("should be zero", function () {
        expect(testNum).to.equal(0);
    })
  }
  • Related