You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jest中测试抛出的GraphQLError?

解决Jest测试GraphQLError抛出错误的问题

问题原因

你当前的toThrow用法错误——Jest中toThrow如果传入函数参数,它会把这个函数当作错误的构造函数,检查抛出的错误是否是该构造函数的实例。但你传的是一个匿名断言函数,Jest无法识别它作为构造函数,因此抛出"Expected constructor name is an empty string"的错误。

解决方案

下面提供两种可行的测试方式:

方式一:捕获错误后逐一断言

先验证抛出的错误类型,再捕获错误实例,断言它的message和extensions.code属性:

import { GraphQLError } from 'graphql';
import { test } from './your-module-path';

test('抛出正确的NOT_FOUND错误', () => {
  // 先验证错误类型
  expect(() => test()).toThrow(GraphQLError);

  // 捕获错误并断言细节
  try {
    test();
  } catch (err) {
    const error = err as GraphQLError;
    expect(error.message).toBe('no item found');
    expect(error.extensions?.code).toBe('NOT_FOUND');
  }
});

方式二:使用toThrowError结合对象匹配器

用Jest的expect.objectContaining匹配器,一次性验证错误的所有关键属性:

import { GraphQLError } from 'graphql';
import { test } from './your-module-path';

test('抛出的错误包含正确的消息和错误码', () => {
  expect(() => test()).toThrowError(expect.objectContaining({
    message: 'no item found',
    extensions: expect.objectContaining({
      code: 'NOT_FOUND'
    })
  }));
});

补充说明

如果需要同时严格验证错误类型和属性,可以结合expect.any:

test('抛出类型和属性都正确的GraphQLError', () => {
  expect(() => test()).toThrowError(expect.objectAssign(
    expect.any(GraphQLError),
    {
      message: 'no item found',
      extensions: { code: 'NOT_FOUND' }
    }
  ));
});

内容的提问来源于stack exchange,提问作者Owen Murphy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 14:22:49