开玩笑-期望抛出消息测试

时间:2018-12-16 20:07:08

标签: javascript node.js unit-testing jestjs

我正在尝试编写测试以测试是否引发了错误

A = [170,170,150]
b = 160
C = [2,1]
xb = [b/(k-1) if k!=1 else 0 for k in C]
print(xb)

我写的测试按预期工作

exports.handler = async data => {
  try {
      throw new Error("Invalid Data")
    };
  } catch (err) {
    throw err;
  }
};

如何避免在测试中使用try / catch块?

2 个答案:

答案 0 :(得分:1)

您可以使用.rejects助手:

it("Throw Error Invalid Data", () => {
  return expect(handler({})).rejects.toEqual(new Error("Invalid Data"));
});

或具有异步功能:

it("Throw Error Invalid Data", async () => {
  await expect(handler({})).rejects.toEqual(new Error("Invalid Data"));
});

答案 1 :(得分:0)

this

await expect(handler({})).rejects.toThrow(new Error("Invalid Data"));