网站搜索

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


我遇到了一个函数抛出字符串的情况。

我知道在 Jest 中我们有 toThrow 匹配器,它允许我们测试函数确实会抛出异常。但是这个匹配器只有在抛出的对象是 Error 时才有效。

是否可以使用 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');
  });
});

返回

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')),那么它就能工作。

答案#1

.reject 制作期望以测试被拒绝的值,因此您可以在这里使用标准的 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
  });
});