Ditiz
Ditiz

Reputation: 171

Change the value of a global variable use in the function I test

Is it possible to change the value of a global variable when I test a function that uses it?

My code:

let check = false;

function myFunction () {
  if (check) {
   doStuff();
  } else {
    doOtherStuff();
  }
}

My test:

describe("test myFunction", () => {
  it("should call doStuff", () => {
    doStuff = jest.fn();

    myFunction();

    expect(doStuff).toBeCalled();
  });
});

I want my test to execute doStuff instead of doOtherStuff, there is a way to mocking the function that allows me to do that?

Upvotes: 0

Views: 644

Answers (1)

Lin Du
Lin Du

Reputation: 102237

As @jfriend00 said,

the variable check is not a global variable in node.js. That variable has module scope, not global scope.

If you want to make check as a global variable, you need use global namespace object.

Here is one solution for your example:

index.ts:

(global as any).check = false;

export const doStuff = () => 'doStuff';
export const doOtherStuff = () => 'doOtherStuff';

export function myFunction() {
  if ((global as any).check) {
    doStuff();
  } else {
    doOtherStuff();
  }
}

index.spec.ts:

import * as funcs from './';

describe('myFunction', () => {
  afterEach(() => {
    // restore to original value if needed
    (global as any).check = false;
  });
  it('should call doOtherStuff', () => {
    const doOtherStuffSpy = jest.spyOn(funcs, 'doOtherStuff');
    funcs.myFunction();
    expect(doOtherStuffSpy).toBeCalled();
  });

  it('should call doStuff', () => {
    (global as any).check = true;
    const doStuffSpy = jest.spyOn(funcs, 'doStuff');
    funcs.myFunction();
    expect(doStuffSpy).toBeCalled();
  });
});

unit test result with 100% coverage:

 PASS  src/stackoverflow/58454044/index.spec.ts (8.829s)
  myFunction
    ✓ should call doOtherStuff (5ms)
    ✓ should call doStuff (1ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.433s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58454044

Upvotes: 1

Related Questions