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

测试布尔值翻转时遇TypeError: Cannot read properties of undefined (reading 'rpc')错误

错误排查:TypeError: Cannot read properties of undefined (reading 'rpc')

核心原因

program变量未被正确初始化,处于undefined状态,导致无法读取其rpc属性。

可能的原因及解决方法

1. 测试文件未正确初始化Anchor Program实例

测试用例执行前,必须完成Provider和Program的初始化:

const anchor = require('@project-serum/anchor');
const { SystemProgram } = anchor.web3;

describe('light', () => {
  // 初始化Provider
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);
  // 从Anchor工作区加载Program(名称需与Anchor.toml中一致,大小写敏感)
  const program = anchor.workspace.Light;

  it('Creates a Flipper', async () => {
    const switchAccount = anchor.web3.Keypair.generate();
    console.log(switchAccount.publicKey.toBase58())
    await program.rpc.initialize({
      accounts: {
        switchAccount: switchAccount.publicKey,
        user: provider.wallet.publicKey,
        system_program: SystemProgram.programId,
      },
      signers: [switchAccount],
    });
  });
});

如果是手动加载IDL和程序ID,需确保路径和ID正确:

const idl = require('../target/idl/light.json');
const programId = new anchor.web3.PublicKey('你的程序公钥');
const program = new anchor.Program(idl, programId, provider);

2. Anchor工作区未正确构建或配置

  • 执行anchor build重新构建程序,确保生成的IDL文件完整且正确。
  • 检查Anchor.toml中的[programs.localnet]配置,确保程序ID与测试代码中使用的一致;若使用anchor.workspace加载,则需保证程序名称匹配。

3. 测试环境未连接到Solana本地节点

  • 启动本地测试节点:执行solana-test-validator。
  • 确认Provider连接地址正确,可手动指定:
const connection = new anchor.web3.Connection('http://localhost:8899');
const provider = new anchor.AnchorProvider(
  connection,
  provider.wallet,
  anchor.AnchorProvider.defaultOptions()
);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:32:23