Caught between the proverbial rock and a hard place.
My app was built using:
t3-stack
:v6.2.1
- T3 stackNext.js
:v12.3.1
jest
:v29.3.1
Followed Next.js documentation for setting up jest with Rust Compiler at https://nextjs.org/docs/testing#setting-up-jest-with-the-rust-compiler
Introduced https://wagmi.sh/ (React Hooks for Ethereum) to my project, smooth sailing until component testing began.
In order to test, created a mocked wagmi client in a test file by importing necessary packages like this:
import { Client, createClient, WagmiConfig, useConnect } from "wagmi";
Upon running the test, encountered an issue:
.../node_modules/wagmi/dist/index.js:2 import { createSyncStoragePersister } from "@tanstack/query-sync-storage-persister"; ^^^^^^
SyntaxError: Cannot use import statement outside a module
Explored various options in jest.config.js including filters and transformIgnorePatterns but no solution for transforming wagmi esm enabled library.
Referenced jest docs and implemented ECMAScript Modules support by adding extensionsToTreatAsEsm: [".ts", ".tsx"] to jest.config.js which allowed running tests with nodejs flag:
NODE_OPTIONS=--experimental-vm-modules npx jest -- src/__tests__/Wallet.test.tsx
Success! Everything worked flawlessly!
Later needed to mock a hook and revisited jest docs on mocking modules in ESM mode, hit a roadblock as I couldn't mock hooks despite trying numerous setups detailed in the issue here.
Reverted to original setup sans ESM support where jest.mock function worked as intended.
However, faced a new challenge of not being able to import wagmi due to its ESM compatibility without ESM support activated.
The question now is how to import npm packages that are ESM modules?