I am trying to create a simple code which splits a string at ','
. The expected string is a list of numbers separated by commas. I have to print the sum of those numbers. My code is here:
function add(numbers) {
if (numbers === "")
{
return 0;
}
else if (typeof parseInt(numbers) == 'number')
{
return parseInt(numbers);
}
else
{
let numArray = numbers.toString().split(',');
console.log(numArray);
let value = numArray.every(checkElement);
if (value) {
return (getSum(numArray));
}
else
{
return "Error in formatting";
}
}
}
function checkElement(element)
{
return (typeof parseInt(element) == 'number')
}
function getSum(numArray)
{
let total = 0;
for (let i = 0; i < numArray.length; i++)
{
total += numArray[i];
}
return total
}
module.exports = add
My Jest code is:
const add = require('../sum.js')
test('Returns sum of numbers', () => {
expect (
add("225,75")
).toBe(300)
})
I am getting this error:
● Returns sum of numbers
expect(received).toBe(expected) // Object.is equality
Expected: 300
Received: 225
17 | add("225,75")
> 18 | ).toBe(300)
| ^
19 | })
at Object.toBe (js/Testing/sum.test.js:18:7)
Moreover, my VS Code is not printing any console.log if I try to run the my js file using node filename.js command. It just starts a new terminal line. Not sure what's going wrong. The error looks like split() isn't working properly - it's only ever returning the 1st element (don't understand why) and VS Code won't print my console logs to check where it is stuck.