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

Anchor CLI 0.26.0初始化项目后测试报TypeError问题求助

问题描述

环境配置:anchor-cli 0.26.0、Node v16.16.0(npm v8.11.0)
执行anchor init hello-world完成项目初始化,cd hello-world && anchor build编译成功,但未修改任何代码直接运行anchor run test时,在测试文件tests/hello-world.ts第13行触发错误:

TypeError: Cannot read properties of undefined (reading 'methods')

测试文件代码如下:

import { Program } from "@project-serum/anchor";
import { HelloWorld } from "../target/types/hello_world";

describe("hello-world", () => {
  // Configure the client to use the local cluster.
  anchor.setProvider(anchor.AnchorProvider.env());

  const program = anchor.workspace.HelloWorld as Program<HelloWorld>;

  it("Is initialized!", async () => {
    // Add your test here.
    const tx = await program.methods.initialize().rpc();
    console.log("Your transaction signature", tx);
  });
});

已尝试排查操作:更换Node LTS 16.16.0、在干净目录重新操作、检查TypeScript安装状态、提前执行yarn install、确认Solana密钥对和JSON文件位置正确,问题仍未解决。

解决方案
  • 对齐Anchor依赖版本
    打开项目根目录的package.json,检查dependencies中的@project-serum/anchor版本是否为^0.26.0。若版本不匹配,执行yarn add @project-serum/anchor@0.26.0或npm install @project-serum/anchor@0.26.0完成版本对齐。

  • 校验程序ID配置一致性

    1. 执行anchor build后,查看target/idl/hello_world.json中metadata.address字段的程序ID。
    2. 检查项目根目录Anchor.toml内[programs.localnet]下的hello_world地址,确保与上述ID完全一致。
    3. 确认测试文件中未手动修改程序ID,保证anchor.workspace.HelloWorld能正确加载IDL和程序地址。
  • 确保本地Solana节点正常运行
    测试依赖本地Solana节点服务,执行solana-test-validator启动本地节点,保持窗口开启后重新运行anchor run test。

  • 重新生成IDL与类型定义
    删除target目录后重新编译,确保IDL和类型文件正确生成:

    rm -rf target && anchor build
    
  • 修正Provider初始化逻辑
    部分场景下,直接使用anchor.AnchorProvider.env()可能导致Provider加载异常,可显式创建Provider修改测试代码:

    import { Program, AnchorProvider, setProvider } from "@project-serum/anchor";
    import { HelloWorld } from "../target/types/hello_world";
    import { Connection, Keypair } from "@solana/web3.js";
    
    describe("hello-world", () => {
      // 显式创建Provider实例
      const connection = new Connection("http://localhost:8899");
      const wallet = Keypair.generate();
      const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed" });
      setProvider(provider);
    
      const program = anchor.workspace.HelloWorld as Program<HelloWorld>;
    
      it("Is initialized!", async () => {
        const tx = await program.methods.initialize().rpc();
        console.log("Your transaction signature", tx);
      });
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:25:47