Normally we get the ethereum provider from a wallet extension. Running tests in headless mode means we have no extensions installed => no ethereum provider. This script will inject a customized provider with a wallet that signs transactions automatically. It can:
- send transactions
- sign transactions
- request accounts
- contract calls
For now, it only works for Mumbai, but you can easily customize it to work with
other chains by changing the rpc url
and the chain id
(0x13881
).
-
Initialize a var called
PRIVATE_KEY
inside an .env file -
Run
npm run bundle
to compileindex.js
with webpack -
The result is
bundle
. -
Open
test.html
and console logwindow.ethereum
to test the code. -
Copy this file in the project where you use
Playwright
. Usage:await page.addInitScript({ path: './bundle/734.provider.js' }); await page.addInitScript({ path: './bundle/895.provider.js' }); await page.addInitScript({ path: './bundle/provider.js' });
-
Test if it works:
expect(await page.evaluate(() => window['ethereum'])).toBeTruthy();
-
You can mimic
MetaMask
or other wallets by changing the wallet field (isMetaMask
,isCoinbaseWallet
, etc.) fromindex.js
.
Warning: The provider.js
file will contain your private key.