玩笑测试,保持 return 未定义?

Jest testing, keeps return undefined?

我想开玩笑地测试一个函数,我只是想知道哪里出了问题?它一直说它期望 return 输出,但未定义。我已经在其他地方测试了该函数,它似乎 return 是正确的数组。

我正在调用我的函数并向它传递一个对象,然后它应该 return 一个数组。然后我调用 .toEqual(output) 这是一个数组。

//This is my function
const allAddresses = [
];

const updateAllAddresses = (obj) => {
  const transferAmount = obj.transferAmount;
  const to = obj.to;
  const transferAddress = obj.address;
  const newBalance = obj.newBalance;
  const addressArr = [...allAddresses];
  console.log("This addressArr", addressArr);
  console.log("this is obj", obj);
  //To set your account to the new balance after transfer and
  //to check if the address you transfer to is your own account
  addressArr.map((address) => {
    if (address.account === transferAddress) {
      console.log("This is inside the map !!!!");
      address.balance = Number(newBalance);
    }
    if (address.account === to) {
      console.log("2");
      address.balance = Number(transferAmount) + Number(address.balance);
    }
    console.log("last part of the testing", addressArr);
    return addressArr;
  });
};

const obj = {
};
const output = [
];


//This is my test
describe("Update array", () => {
  test("update the array with the new information", () => {
    expect(updateAllAddresses(obj)).toEqual(output);
  });
});

您的 updateAllAddresses 方法有问题。 你没有返回任何东西然后你的函数的结果变成 undefined;

return 添加到您使用 .map 方法的位置。

  return addressArr.map((address) => {
    if (address.account === transferAddress) {
      console.log("This is inside the map !!!!");
      address.balance = Number(newBalance);
    }
    if (address.account === to) {
      console.log("2");
      address.balance = Number(transferAmount) + Number(address.balance);
     }
    console.log("last part of the testing", addressArr);
    return address;
  });

您不能在 map 函数内短路和 return。您应该 return map

之后的对象

此外,当您在 map 中更改 address 时;它真的没有改变任何东西,因为 address 变量将在下一次迭代时从内存中删除