Home > other >  Jest mock an internal variable inside a function
Jest mock an internal variable inside a function

Time:02-04

Im just learning jest unit testing. Im running into an issue. I want to check the result of a function with sum of two numbers without having a return statement.

function sum(a,b){
var res = a b;
return true;
}

test('sum of numbers', () => {
expect(sum(1,2)).toBe(res)
});

how to get the value of the res variable in my test. Pleasee let me know. Thanks.

CodePudding user response:

The test should be testing the result of the function. You can not access variables inside of a function since the varaibles scope is to the function block and it is not global.

You function should be returning the result from the function and your test should be testing what you expect the output to be.

function sum(a,b){
  var res = a   b;
  return res;
  // return a   b;
}
test('sum of numbers', () => {
  expect(sum(1,2)).toBe(3)
});

CodePudding user response:

Testing implementation details like this is an anti-pattern in regards to frontend testing. You should be testing the user interaction that calls this function (eg. a button click). Then, check whether the rendered text on the screen is your desired result (ex. 1 1=2).

Project requirements that dictate a function is tested directly, are quite simply wrong.

CodePudding user response:

Basic test case for your sum function

test('sum of numbers', () => {
expect(sum(1,2)).toBe(3)
});

or you can use toEqual at the place of toBe.

Even you can check this post https://jestjs.io/docs/getting-started.

CodePudding user response:

I have a few suggestions for you. To get the res value, you can try using a reference type like a JavaScript object.

function sum(a,b, obj){
  var res = a b;
  obj.res = res;
  return true;
}

test('sum of numbers', () => {
  let obj = {};
  expect(sum(1, 2, obj)).toBe(true)

  expect(obj.res).toBe(5);
});

OR

Another option is to return an object from the function, which would include the boolean value you need to test, along with the internal variable.

function sum(a,b){
  var res = a b;
  return {
    res,
    val: true
  };
}

test('sum of numbers', () => {
  const {res, val} = sum(2, 3);
  expect(val).toBe(true)
  expect(res).toBe(5);
});

I noticed in one of your comments on a post that you mentioned

Its a requirement in my project. I have to test an internal variable value inside a function

Just double checking, is it possible that the requirement is actually asking you to return the local variable and compare it, instead of a boolean? If so, you can follow the method outlined in @epascarello's answer. Hope that helps!

  • Related