如何测试使用 Jest 抛出的字符串

How to test a String thrown using Jest

我运行遇到函数抛出字符串的情况。

我知道开玩笑说我们有 toThrow 匹配器,它允许我们测试函数是否确实抛出。 但是这个匹配器只有在抛出错误时才起作用。

是否可以使用 Jest 验证字符串是否被抛出?

以下代码

async function funToTest(): Promise<number> {
  if (Math.random()) throw 'ERROR_CODE_X';
  return 10;
}

describe('funToTest', () => {
  it('should throw `ERROR_CODE_X`', () => {
    await expect(() => funToTest()).rejects.toThrow('ERROR_CODE_X');
  });
});

returns

funToTest › should throw `ERROR_CODE_X`

    expect(received).rejects.toThrow(expected)

    Expected substring: "ERROR_CODE_X"

    Received function did not throw

这清楚地表明它没有抛出而函数抛出。

如果我们将其更改为错误 (throw new Error('ERROR_CODE_X')),则它会起作用。

.reject make expect 测试被拒绝的值所以你可以在这里使用标准的期望匹配

async function funToTest(): Promise<number> {
  throw "ERROR_CODE_X";
}
async function funToError(): Promise<number> {
  throw new Error("ERROR_CODE_X");
}

describe("funToTest", () => {
  it("should throw `ERROR_CODE_X`", async () => {
    //await expect(() => funToTest()).rejects.toThrowErrorMatchingSnapshot();
    // ^^^ not ok: undefined in snapshot
    await expect(() => funToTest()).rejects.toMatchSnapshot();
    await expect(() => funToTest()).rejects.toEqual("ERROR_CODE_X");
  });
  it("should not throw `ERROR_CODE_X`", async () => {
    await expect(() => funToError()).rejects.toThrowErrorMatchingSnapshot();

    await expect(() => funToError()).rejects.toEqual("ERROR_CODE_X");
    //fail here: rejects return a Error
  });
});