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配置一致性
- 执行
anchor build后,查看target/idl/hello_world.json中metadata.address字段的程序ID。 - 检查项目根目录
Anchor.toml内[programs.localnet]下的hello_world地址,确保与上述ID完全一致。 - 确认测试文件中未手动修改程序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

