Solana Devnet Anchor测试报reading 'local'未定义TypeError
Anchor测试报错
Cannot read properties of undefined (reading 'local')解决 报错信息
TypeError: Cannot read properties of undefined (reading 'local') at Suite.<anonymous> (/home/benny/mycalcdapp/tests/mycalcdapp.ts:6:36) at Object.create (/home/benny/mycalcdapp/node_modules/mocha/lib/interfaces/common.js:148:19) at context.describe.context.context (/home/benny/mycalcdapp/node_modules/mocha/lib/interfaces/bdd.js:42:27) at Object.<anonymous> (/home/benny/mycalcdapp/tests/mycalcdapp.ts:5:1) at Module._compile (node:internal/modules/cjs/loader:1105:14) at Module.m._compile (/home/benny/mycalcdapp/node_modules/ts-node/src/index.ts:439:23) at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
报错触发位置在测试文件第6行const provider = anchor.Provider.local();,本质原因是调用的anchor.Provider对象不存在,属于Anchor版本与API写法不匹配问题。
根因说明
Anchor在0.25版本后做了两个破坏性变更:
- 官方包名从
@project-serum/anchor迁移为@coral-xyz/anchor - 原有的
Provider类重命名为AnchorProvider,旧的anchor.Provider挂载点被移除
如果本地安装的是0.25以上的新版Anchor,却沿用旧版教程里的包名和anchor.Provider.local()写法,就会触发这个undefined错误。
另外原测试代码里还有两处后续会触发问题的小错误: - 调用create方法时传入的字符串写为
Welocme to solana,和断言里的Welcome to solana拼写不一致,会导致断言失败 - 新版Anchor废弃了
program.rpc.xxx()的直接调用写法,改为链式调用风格
排查步骤
- 在项目根目录执行
npm list @project-serum/anchor @coral-xyz/anchor,确认当前安装的Anchor包名和版本 - 确认测试前本地已启动
solana-test-validator节点,且Anchor.toml中provider配置指向本地节点
解决方法
方案1:升级到新版Anchor(推荐)
- 替换依赖包:
npm uninstall @project-serum/anchor npm install @coral-xyz/anchor@latest
- 修改测试文件代码为适配新版的写法:
const assert = require('assert'); // 替换为新包名引入 const anchor = require('@coral-xyz/anchor'); const { SystemProgram } = anchor.web3; describe('mycalcdapp', () => { // 替换为新版AnchorProvider const provider = anchor.AnchorProvider.local(); anchor.setProvider(provider); const calculator = anchor.web3.Keypair.generate(); const program = anchor.workspace.mycalcdapp; it('creates a calculator', async () => { // 新版链式调用写法,修正拼写错误 await program.methods.create('Welcome to solana') .accounts({ calculator: calculator.publicKey, user: provider.wallet.publicKey, systemProgram: SystemProgram.programId, }) .signers([calculator]) .rpc(); const account = await program.account.calculator.fetch(calculator.publicKey); assert.ok(account.greeting === 'Welcome to solana'); }); });
方案2:锁定旧版Anchor兼容原有代码
如果不想修改现有API写法,直接安装兼容旧API的最后一个版本即可:
npm install @project-serum/anchor@0.24.2
安装完成后只需要修正代码里Welocme的拼写错误,不需要调整其他API写法即可正常运行测试。
内容的提问来源于stack exchange,提问作者risky last
相关产品推荐
相关产品推荐

