【发布时间】: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