Jest.js 尝试使用expect().toThrow测试GraphQLError

cnh2zyt3  于 2023-08-01  发布在  Jest
关注(0)|答案(1)|浏览(117)

我有一个GraphQLError,如下所示:

export const notFoundError = (msg: string): GraphQLError => {
    return new GraphQLError(msg, {
        extensions: { code: "NOT_FOUND" }
    });
};

字符串
假设一个函数抛出了这个错误

export function test() {
    throw notFoundError("no item found")
}


我怎么测试这是玩笑?比如:

expect(() => {
test();
}).toThrow((error: GraphQLError) => {
    // expect statements to test the message and code
})


我尝试了这个,然而,我得到一个错误说

expect(received).toThrow(expected)

    Expected constructor name is an empty string
    Received constructor: GraphQLError

    Received message: "no item found"

          2 |
          3 | export const notFoundError = (msg: string): GraphQLError => {
        > 4 |     return new GraphQLError(msg, {
            |            ^
          5 |         extensions: { code: "NOT_FOUND" }
          6 |     });
          7 | };


任何帮助都欢迎!

jgovgodb

jgovgodb1#

根据https://jestjs.io/docs/expect#tothrowerror上的文档
应该是这样的:

test('test notFoundError', () => {
  const notFoundError = (msg: string): GraphQLError => {
    throw new GraphQLError(msg, {
      extensions: { code: "NOT_FOUND" }
    });
  };

  expect(() => notFoundError("no item found")).toThrow(new GraphQLError("no item found", {
    extensions: { code: "NOT_FOUND" }
  }));

});

字符串
注意:看起来这只匹配消息

相关问题