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

运行Cypress测试时如何清除填满控制台的Apollo错误

解决Apollo Client控制台大量错误的屏蔽方案

方案1:通过Apollo Client错误链路拦截

在创建Apollo Client实例时,添加onError链接过滤目标错误:

import { ApolloClient, InMemoryCache, createHttpLink, from } from '@apollo/client';
import { onError } from '@apollo/client/link/error';

const errorLink = onError(({ graphQLErrors, networkError }) => {
  // 过滤包含特定链接前缀的错误
  const shouldLog = !(
    graphQLErrors?.some(err => err.message.includes('https://go.apollo.dev/c/err')) ||
    networkError?.message.includes('https://go.apollo.dev/c/err')
  );
  
  if (shouldLog) {
    if (graphQLErrors) {
      graphQLErrors.forEach(({ message, locations, path }) =>
        console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
      );
    }
    if (networkError) console.error(`[Network error]: ${networkError}`);
  }
});

const httpLink = createHttpLink({ uri: '/graphql' });

const client = new ApolloClient({
  link: from([errorLink, httpLink]),
  cache: new InMemoryCache(),
});

方案2:全局覆盖console.error过滤错误

在Cypress支持文件(如cypress/support/e2e.js)中,测试启动前覆盖console.error:

before(() => {
  const originalError = console.error;
  console.error = (...args) => {
    const isTargetError = args.some(arg => 
      typeof arg === 'string' && arg.includes('https://go.apollo.dev/c/err')
    );
    if (!isTargetError) {
      originalError.apply(console, args);
    }
  };
});

方案3:调整graphql-codegen Mock配置

若错误来自模拟数据,修改codegen.yml配置:

generates:
  src/generated/graphql.ts:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
      - typescript-mock-data
    config:
      noSchemaMock: true # 关闭自动生成可能触发错误的mock resolver

也可自定义mock resolver,确保返回符合Schema的合法数据,减少Apollo错误触发。

方案4:配置Cypress的failOnConsoleError插件

使用cypress-fail-on-console-error时,在cypress.config.js添加过滤规则:

const { defineConfig } = require('cypress');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      require('cypress-fail-on-console-error')(on, {
        filter: (error) => !error.message.includes('https://go.apollo.dev/c/err'),
      });
    },
  },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:44:57