【问题标题】:Jest (Received function did not throw, Error handling)开玩笑(接收到的函数没有抛出,错误处理)
【发布时间】:2021-05-22 02:30:24
【问题描述】:

我现在遇到了 Jest 处理错误的问题。

我的代码:

export class ResistorColor {
  private colors: string[];

  constructor(colors: string[]) {
    this.colors = colors;
  }
  Obj: any = {
    black: "0",
    brown: "1",
    red: "2",
    orange: "3",
    yellow: "4",
    green: "5",
    blue: "6",
    violet: "7",
    grey: "8",
    white: "9",
  };
  value = (): number => {
    let result = "";
    if (this.colors.length < 2) {
      throw new Error("At least two colors need to be present");
    }
    this.colors.length = 2;
    for (let a = 0; a < this.colors.length; a++) {
      for (let i in this.Obj) {
        if (this.colors[a] === i) {
          result += this.Obj[i];
        }
      }
    }
    return parseInt(result);
  };
}

我的测试文件是:

import { ResistorColor } from "./resistor-color-duo";

describe("Resistor Colors", () => {
  it("Brown and black", () => {
    const resistorColor = new ResistorColor(["brown", "black"]);
    expect(resistorColor.value()).toEqual(10);
  });

  it("Blue and grey", () => {
    const resistorColor = new ResistorColor(["blue", "grey"]);
    expect(resistorColor.value()).toEqual(68);
  });

  it("Yellow and violet", () => {
    const resistorColor = new ResistorColor(["yellow", "violet"]);
    expect(resistorColor.value()).toEqual(47);
  });

  it("Orange and orange", () => {
    const resistorColor = new ResistorColor(["orange", "orange"]);
    expect(resistorColor.value()).toEqual(33);
  });

  it("Ignore additional colors", () => {
    const resistorColor = new ResistorColor(["green", "brown", "orange"]);
    expect(resistorColor.value()).toEqual(51);
  });

  it("Throws error when not enough colors", () => {
    expect(() => new ResistorColor(["green"])).toThrowError(Error);
  });
});

我已经通过了 5 个案例,直到最后一个关于抛出错误的案例。

当我检查 If 语句时,它应该会抛出一个错误。

我读过:

JEST Received function did not throw, but HTTPError is thrown

Error is thrown but Jest's `toThrow()` does not capture the error

但这似乎不是我的问题。

然后我收到了。

expect(received).toThrowError(expected)

    Expected constructor: Error

    Received function did not throw

我是 typescript 和 Jest 的新手,任何帮助都将不胜感激。

【问题讨论】:

    标签: javascript typescript jestjs


    【解决方案1】:

    Jest 很难不注意到错误,问题是它真的没有被抛出。在这种情况下,它不是在构造函数中抛出,而是在 value 中抛出,它没有被调用。

    应该是:

    const resistorColor = new ResistorColor(["green"]);
    expect(() => resistorColor.value()).toThrowError(Error);
    

    【讨论】:

      猜你喜欢
      • 2018-09-27
      • 2021-09-07
      • 2021-07-22
      • 2021-07-13
      • 2018-07-20
      • 1970-01-01
      • 2023-02-08
      • 1970-01-01
      • 2020-12-30
      相关资源
      最近更新 更多