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

使用Jest测试TypeGraphQL API时遇无效/意外令牌错误求助

解决GraphQL单元测试中的SyntaxError问题

问题描述

编写GraphQL API单元测试时,运行测试出现SyntaxError: Invalid or unexpected token错误,错误指向buildSchema配置行。相关代码及错误信息如下:

测试文件代码

import { graphql } from "graphql";
import { createSchema } from "../src/schema";

describe("BlacklistResolver", () => {
  it("fetches blacklist", async () => {
    const schema = await createSchema();
    const query = `
  query GetBlacklist($organisationId: String!) {
    getBlacklist(organisationId: $organisationId)
  }
`;

    const variables = {
      organisationId: "ab5e2add-c209-4f4c-8d65-8144bc1e741d" // Replace with the desired ID
    };

    const expectedResult = {
      data: {
        getBlacklist: ["item1", "item2", "item3"]
      }
    };

    const result = await graphql({
      schema,
      source: query,
      variableValues: variables
    });

    expect(result).toEqual(expectedResult);
  });
});

Schema构建代码(原版本)

import { buildSchema } from "type-graphql";

export async function createSchema() {
  const schema = await buildSchema({
    resolvers: [`${__dirname.replace(/\\/g, "/")}/resolvers/**/*.ts`],
    validate: false,
    emitSchemaFile: true
  });
  return schema;
}

错误信息

SyntaxError: Invalid or unexpected token

      11 | export async function createSchema() {
    > 12 |   const schema = await buildSchema({
         |                                   ^
      13 |     resolvers: [`${__dirname.replace(/\\/g, "/")}/resolvers/**/*.ts`],
      14 |     validate: false,
      15 |     emitSchemaFile: true

尝试添加.babelrc配置、改用buildSchemaSync后问题依旧。

解决方案

1. 修正路径处理逻辑

手动替换__dirname斜杠易引入转义问题,改用Node.js内置path模块处理路径,保证跨平台兼容性:

import { buildSchema } from "type-graphql";
import path from "path";

export async function createSchema() {
  const schema = await buildSchema({
    resolvers: [path.join(__dirname, "resolvers", "**", "*.ts")],
    validate: false,
    emitSchemaFile: true
  });
  return schema;
}

2. 配置测试环境支持TypeScript

若使用Jest测试框架,需通过ts-jest编译TypeScript文件,创建jest.config.js:

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  moduleFileExtensions: ["ts", "js"],
  transform: {
    "^.+\\.ts$": "ts-jest"
  },
  testMatch: ["**/__tests__/**/*.ts", "**/?(*.)+(spec|test).ts"]
};

同时安装依赖:

npm install --save-dev ts-jest jest typescript @types/jest

3. 直接导入Resolver类(更可靠)

避免glob路径解析的潜在问题,直接导入Resolver类到Schema构建函数:

import { buildSchema } from "type-graphql";
import { BlacklistResolver } from "./resolvers/BlacklistResolver";
// 按需导入其他Resolver

export async function createSchema() {
  const schema = await buildSchema({
    resolvers: [BlacklistResolver], // 直接传入Resolver类数组
    validate: false,
    emitSchemaFile: true
  });
  return schema;
}

4. 检查TypeScript配置

确保tsconfig.json包含必要编译选项:

{
  "compilerOptions": {
    "target": "ES6",
    "module": "CommonJS",
    "lib": ["ES6"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

原因分析

错误核心原因:

  • 手动处理路径时引入无效转义字符,导致解析失败;
  • 测试环境未正确编译TypeScript文件,直接解析.ts中的装饰器、ES模块语法时出错;
  • glob路径在测试环境中无法被正确解析,导致type-graphql无法加载Resolver文件。

内容的提问来源于stack exchange,提问作者Lucas Fab

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 07:00:37