简体   繁体   中英

Jest (Received function did not throw, Error handling)

I now have a problem with Jest handling Error.

My code:

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);
  };
}

my test file is:

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);
  });
});

I've passed 5 cases until the last case about throwing an Error.

It's should throw an Error while I'm checking in If statement.

I've read:

JEST Received function did not throw, but HTTPError is thrown

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

But it seems not likely my problem.

and then I received.

expect(received).toThrowError(expected)

    Expected constructor: Error

    Received function did not throw

I'm new to typescript and Jest, any helps would be Appreciated.

It would be hard for Jest to not notice an error, the problem is that it is really not thrown. In this case it's thrown not in constructor but in value , which is not called.

It should be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM