Search code examples
javascriptunit-testingsinonsinon-chai

sinon chai - expect value defined in global scope


I have a file that contains a class as well as some globally defined variables. Here's a simplified version:

let globalVar = 0;

export default class Example {
  ...
  ...

  run() {
    this.key1 = 123;
    this.key2 = 345;
    this.key3 = 567;

    globalVar += 1;    
  }
}

I want to test the value of this variable as well as some values that are actually set on the class itself.

  it('should set values when run() is run', () => {
    example.values = {
      key1: 123,
      key2: 345,
      key3: 567,
    };

    example.run();

    expect(example.values.key1).to.eql(123);
    expect(example.values.key2).to.eql(345);
    expect(example.values.key3).to.eql(567);


    expect(globalVar).to.eql(1);
  });

The this values pass, but the global variable fails. I also tried setting this on the global object for Node:

expect(global.globalVar).to.eql(1);

Solution

  • every file in node has its own scope so the globalVar can't be accessed directly from the test file with just expect(globalVar).to.eql(1);

    The workaround is we can create a function that returns globalVar for example:

    // src.js
    
    let globalVar = 0;
    
    export default class Example {
      ...
      ...
    
      run() {
        this.key1 = 123;
        this.key2 = 345;
        this.key3 = 567;
    
        globalVar += 1;    
      }
    
      getGlobalVar() { // adding a new method here
        return globalVar;
      }
    }
    

    later on, in the test file

    expect(example.globalVar()).to.eql(1);
    

    Hope it helps