Here are the steps to automate Metamask in Cypress:
- Install Metamask browser extension in your browser
- Install the
cypress-browser-extension
plugin in your Cypress project by running the following command in your terminal:npm install cypress-browser-extension
- Import the plugin in your
cypress/plugins/index.js
file:const browserExtension = require('cypress-browser-extension') module.exports = (on, config) => { browserExtension.install(on, config) }
- In your Cypress test file, check if Metamask is installed and unlocked:
cy.wrap(window.ethereum).then((ethereum) => { if (ethereum) { ethereum.request({ method: 'eth_requestAccounts' }).then((accounts) => { if (accounts.length === 0) { ethereum.enable().then(() => { cy.log("Metamask is unlocked") }) } else { cy.log("Metamask is already unlocked") } }) } else { cy.log("Metamask is not installed") } })
This code checks if Metamask is installed by checking if
window.ethereum
is available, and then requests the user’s accounts. If there are no accounts, it will prompt the user to unlock Metamask. If there are accounts, it logs that Metamask is already unlocked. - Now you can use Cypress to interact with Metamask, for example, to sign a transaction:
cy.wrap(window.ethereum).then((ethereum) => { const from = ethereum.selectedAddress const to = '0x2f8a2c15d708828a8601ed22c099bfdc7de4882e' const value = '1000000000000000000' // 1 ETH const data = '0x' ethereum.request({ method: 'eth_sendTransaction', params: [{ from, to, value, data }] }).then((txHash) => { cy.log("Transaction hash: ${txHash}") }) })
This code gets the selected address from Metamask, defines the recipient address, value, and data for a transaction, and then sends the transaction using the
eth_sendTransaction
method. The returned transaction hash is logged in the console.That’s it! With these steps, you should be able to automate Metamask in Cypress.
Leave a comment