如何使用Jest测试多个返回值

huangapple go评论59阅读模式
英文:

How to test multiple return values, using Jest

问题

I'm looking manipulate values from a byte stream. I will receive values in an array, that I'm looking to parse. I'm looking to return a dictionary with the new formatted results. My formatting code is called index.js

//index.js
function calculateNumbers(numbers)
{   
  results={};
  
  //Summing two values
  sumOfTwo = numbers[0] + numbers[1];  //should be 6
  results.valTwo = sumOfTwo;

  //Summing three values
  sumOfThree = numbers[0] + numbers[1] + numbers[3]; //should be 9
  results.valThree = sumOfThree;

  return{
    total:results
  };
}

module.exports = calculateNumbers;

For testing I want create a test script to validate my responses (Shown in index.test.js.)

In my function I'm returning {value:total}; When returning my values in this format my test code returns saying:

 Expected: 3
    Received: {"value": {"valThree": NaN, "valTwo": 3}}
//index.test.js
const calculateNumbers= require("./index");
test("Returns calculations",() => {
    //expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
    expect(calculateNumbers([1,2,6])).toBe(3,9);
});

How can I modify my unit test to parse the new returned value ?

英文:

I'm looking manipulate values from a byte stream. I will receive values in an array, that I'm looking to parse. I'm looking to return a dictionary with the new formatted results. My formatting code is called index.js

//index.js
function calculateNumbers(numbers)
{   
  results={};
  
  //Summing two values
  sumOfTwo = numbers[0] + numbers[1];  //should be 6
  results.valTwo = sumOfTwo;

  //Summing three values
  sumOfThree = numbers[0] + numbers[1] + numbers[3]; //should be 9
  results.valThree = sumOfThree;

  return{
    total:results
  };
}

module.exports = calculateNumbers;

For testing I want create a test script to validate my responses (Shown in index.test.js.)

In my function I'm returning {value:total}; When returning my values in this format my test code returns saying:

 Expected: 3
    Received: {"value": {"valThree": NaN, "valTwo": 3}}
//index.test.js
const calculateNumbers= require("./index");
test("Returns calculations",()=> {
    //expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
    expect(calculateNumbers([1,2,6])).toBe(3,9);

});

How can I modify my unit test to parse the new returned value ?

答案1

得分: 0

函数的结果是一个对象。你需要断言所有对象:

expect(calculateNumbers([1,2,6])).toStrictEqual({
  total: {
    valTwo: 3,
    valThree: 9,
  },
});
英文:

Result of your function is object. You need to assert all object:

expect(calculateNumbers([1,2,6])).toStrictEqual({
  total: {
    valTwo: 3,
    valThree: 9,
  },
});

huangapple
  • 本文由 发表于 2023年3月31日 19:36:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定