Mocking a class with Jest which returns another class

Viewed 23

I come from a C# NUnit background so I am struggling to make sense of how to mock imports using Jest in TypeScript.

In my method that I want to test, I've got a call to a module which then returns a class. This then goes on and calls a couple other functions before returning the list that I want.

import { Metaplex, Nft } from "@metaplex-foundation/js-next"

async doSomething(walletAddress: string): Promise<MyType>
{
  const metaplex = Metaplex.make(QuickNodeService.connection)
  const data = await metaplex
    .nfts()
    .findAllByOwner(new PublicKey(walletAddress))
  // carry on doing stuff with the data
}

I have been ripping my hair out trying to figure out how to mock Metaplex and add some well needed unit tests in. I just want to verify that findAllByOwner is called with the correct walletAddress and to mock the return so I can verify what I do with data is correct.

Can anyone help me or point me in the right direction? Thanks in advance!

1 Answers

Don't mock what you don't own.

Make an adapter (a wrapper) and mock that.

Bonus: When you decide to switch to a different dependency in the future, you'll have one chokepoint to modify and test while all the rest of your source code can remain unchanged.

Related