bankrun.test.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import assert from 'node:assert';
  2. import { describe, it } from 'node:test';
  3. import * as anchor from '@coral-xyz/anchor';
  4. import { PublicKey } from '@solana/web3.js';
  5. import { BankrunProvider } from 'anchor-bankrun';
  6. import { startAnchor } from 'solana-bankrun';
  7. import type { CloseAccountProgram } from '../target/types/close_account_program';
  8. const IDL = require('../target/idl/close_account_program.json');
  9. const PROGRAM_ID = new PublicKey(IDL.address);
  10. describe('close-an-account', async () => {
  11. // Configure the client to use the local cluster.
  12. const context = await startAnchor('', [{ name: 'close_account_program', programId: PROGRAM_ID }], []);
  13. const provider = new BankrunProvider(context);
  14. const payer = provider.wallet as anchor.Wallet;
  15. const program = new anchor.Program<CloseAccountProgram>(IDL, provider);
  16. // Derive the PDA for the user's account.
  17. const [userAccountAddress] = PublicKey.findProgramAddressSync([Buffer.from('USER'), payer.publicKey.toBuffer()], program.programId);
  18. it('Create Account', async () => {
  19. await program.methods
  20. .createUser('John Doe')
  21. .accounts({
  22. user: payer.publicKey,
  23. })
  24. .rpc();
  25. // Fetch the account data
  26. const userAccount = await program.account.userState.fetch(userAccountAddress);
  27. assert.equal(userAccount.name, 'John Doe');
  28. assert.equal(userAccount.user.toBase58(), payer.publicKey.toBase58());
  29. });
  30. it('Close Account', async () => {
  31. await program.methods
  32. .closeUser()
  33. .accounts({
  34. user: payer.publicKey,
  35. })
  36. .rpc();
  37. // The account should no longer exist, returning null.
  38. try {
  39. const userAccount = await program.account.userState.fetchNullable(userAccountAddress);
  40. assert.equal(userAccount, null);
  41. } catch (err) {
  42. // Won't return null and will throw an error in anchor-bankrun'
  43. assert.equal(err.message, `Could not find ${userAccountAddress}`);
  44. }
  45. });
  46. });