bankrun.test.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. import IDL from "../target/idl/close_account_program.json" with { type: "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(
  13. "",
  14. [{ name: "close_account_program", programId: PROGRAM_ID }],
  15. [],
  16. );
  17. const provider = new BankrunProvider(context);
  18. const payer = provider.wallet as anchor.Wallet;
  19. const program = new anchor.Program<CloseAccountProgram>(IDL, provider);
  20. // Derive the PDA for the user's account.
  21. const [userAccountAddress] = PublicKey.findProgramAddressSync(
  22. [Buffer.from("USER"), payer.publicKey.toBuffer()],
  23. program.programId,
  24. );
  25. it("Create Account", async () => {
  26. await program.methods
  27. .createUser("John Doe")
  28. .accounts({
  29. user: payer.publicKey,
  30. })
  31. .rpc();
  32. // Fetch the account data
  33. const userAccount =
  34. await program.account.userState.fetch(userAccountAddress);
  35. assert.equal(userAccount.name, "John Doe");
  36. assert.equal(userAccount.user.toBase58(), payer.publicKey.toBase58());
  37. });
  38. it("Close Account", async () => {
  39. await program.methods
  40. .closeUser()
  41. .accounts({
  42. user: payer.publicKey,
  43. })
  44. .rpc();
  45. // The account should no longer exist, returning null.
  46. try {
  47. const userAccount =
  48. await program.account.userState.fetchNullable(userAccountAddress);
  49. assert.equal(userAccount, null);
  50. } catch (err) {
  51. // Won't return null and will throw an error in anchor-bankrun'
  52. assert.equal(err.message, `Could not find ${userAccountAddress}`);
  53. }
  54. });
  55. });