Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ feat: MetaMask setup in Cypress #1157

Merged
merged 12 commits into from
Jul 18, 2024
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ test-results
playwright-report
playwright/.cache

### Cypress
drptbl marked this conversation as resolved.
Show resolved Hide resolved
wallets/metamask/downloads
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use wallets/**/downloads


### Synpress

.cache-synpress
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions wallets/metamask/cypress.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { defineConfig } from 'cypress'
import installSynpress from './src/cypress/installSynpress'

export default defineConfig({
chromeWebSecurity: false,
e2e: {
baseUrl: 'http://localhost:9999',
specPattern: 'test/cypress/**/*.cy.{js,jsx,ts,tsx}',
supportFile: 'src/cypress/support/e2e.{js,jsx,ts,tsx}',
testIsolation: false,
async setupNodeEvents(on, config) {
return installSynpress(on, config)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is installSynpress a good name here?
maybe configureSynpress would be better?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what do you think about "configureBeforeSynpress"?

}
}
})
8 changes: 5 additions & 3 deletions wallets/metamask/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,16 @@
],
"scripts": {
"build": "pnpm run clean && pnpm run build:dist && pnpm run build:types",
"build:cache": "synpress-cache test/wallet-setup",
"build:cache:headless": "synpress-cache test/wallet-setup --headless",
"build:cache:headless:force": "synpress-cache test/wallet-setup --headless --force",
"build:cache": "synpress-cache test/playwright/wallet-setup",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

build:playwright:cache?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

end goal will be to use it for both: Playwright and Cypress

"build:cache:headless": "synpress-cache test/playwright/wallet-setup --headless",
drptbl marked this conversation as resolved.
Show resolved Hide resolved
"build:cache:headless:force": "synpress-cache test/playwright/wallet-setup --headless --force",
"build:dist": "tsup --tsconfig tsconfig.build.json",
"build:types": "tsc --emitDeclarationOnly --project tsconfig.build.json",
"clean": "rimraf dist types",
"test": "vitest run",
"test:coverage": "vitest run --coverage",
"test:e2e:headful": "playwright test",
"test:e2e:headful:cypress": "cypress run --browser chrome --headed",
"test:e2e:headless": "HEADLESS=true playwright test",
"test:e2e:headless:ui": "HEADLESS=true playwright test --ui",
"test:watch": "vitest watch",
Expand All @@ -41,6 +42,7 @@
"@types/fs-extra": "11.0.4",
"@types/node": "20.11.17",
"@vitest/coverage-v8": "1.2.2",
"cypress": "13.9.0",
"rimraf": "5.0.5",
"tsup": "8.0.2",
"typescript": "5.3.3",
Expand Down
23 changes: 23 additions & 0 deletions wallets/metamask/src/cypress/MetaMask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { MetaMaskAbstract } from '../type/MetaMaskAbstract'
import Selectors from '../playwright/pages/LockPage/selectors'
import { onboardingPage } from '../selectors';

export class MetaMask extends MetaMaskAbstract {
importWallet() {
cy.get(onboardingPage.GetStartedPageSelectors.termsOfServiceCheckbox).click()
cy.get(onboardingPage.GetStartedPageSelectors.importWallet).click()

cy.get(onboardingPage.AnalyticsPageSelectors.optOut).click()

cy.get(onboardingPage.WalletCreationSuccessPageSelectors.confirmButton).click()

cy.get(onboardingPage.PinExtensionPageSelectors.nextButton).click()
cy.get(onboardingPage.PinExtensionPageSelectors.confirmButton).click()

}

unlock() {
cy.get(Selectors.passwordInput).type(this.password)
cy.get(Selectors.submitButton).click()
}
}
3 changes: 3 additions & 0 deletions wallets/metamask/src/cypress/constants/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const NO_CONTEXT = 'No browser context found. Connect Playwright first - connectPlaywright()'
export const NO_PAGE = 'No page found. Use getPage()'
export const MISSING_INIT = 'EthereumWalletMock not initialized. Use initEthereumWalletMock()'
1 change: 1 addition & 0 deletions wallets/metamask/src/cypress/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './MetaMask'
31 changes: 31 additions & 0 deletions wallets/metamask/src/cypress/installSynpress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { ensureRdpPort } from '@synthetixio/synpress-core'
import { initMetaMask } from './support/initMetaMask'
import setupMetaMaskWallet from './support/setupMetaMaskWallet'

let port: number

export default function installSynpress(on: Cypress.PluginEvents, config: Cypress.PluginConfigOptions) {
const browsers = config.browsers.filter((b) => b.name === 'chrome')
if (browsers.length === 0) {
throw new Error('No Chrome browser found in the configuration')
}

on('before:browser:launch', async (_, launchOptions) => {
// Enable debug mode to establish playwright connection
const args = Array.isArray(launchOptions) ? launchOptions : launchOptions.args
port = ensureRdpPort(args)

args.push(...(await initMetaMask()))

return launchOptions
})

on('before:spec', async () => {
await setupMetaMaskWallet(port)
})

return {
...config,
browsers
}
}
26 changes: 26 additions & 0 deletions wallets/metamask/src/cypress/support/e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// ***********************************************************
// This example support/e2e.ts is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
// import synpressCommands from './synpressCommands'

before(() => {
cy.visit('/')
})

// Cypress.on('uncaught:exception', () => {
// // failing the test
// return false
// })
1 change: 1 addition & 0 deletions wallets/metamask/src/cypress/support/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as unlockWalletForCypress } from './actions/unlockWalletForCypress';
13 changes: 13 additions & 0 deletions wallets/metamask/src/cypress/support/initMetaMask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { prepareExtension } from '../../extensionSetup/prepareExtension'

export async function initMetaMask() {
const metamaskPath = await prepareExtension(false)

const browserArgs = [`--disable-extensions-except=${metamaskPath}`, `--load-extension=${metamaskPath}`]

if (process.env.HEADLESS) {
browserArgs.push('--headless=new')
}

return browserArgs
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { Page } from '@playwright/test'
import { homePage } from '../../../../selectors'

// Closes the popover with news, rainbows, unicorns, and other stuff.
export async function closePopover(page: Page) {
// We're using `first()` here just in case there are multiple popovers, which happens sometimes.
const closeButtonLocator = page.locator(homePage.popover.closeButton).first()

await closeButtonLocator.click()

// TODO: Extract & make configurable
// await clickLocatorIfCondition(closeButtonLocator, () => closeButtonLocator.isVisible(), 1_000)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./closePopover"
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

import { confirmSecretRecoveryPhrase, createPassword } from './helpers'
Fixed Show fixed Hide fixed
import { onboardingPage, homePage } from '../../../../selectors';
import { closePopover } from '../../../../playwright/pages/HomePage/actions';
Fixed Show fixed Hide fixed

export async function importWallet(seedPhrase: string, password: string) {
cy.get(onboardingPage.GetStartedPageSelectors.termsOfServiceCheckbox).click()
cy.get(onboardingPage.GetStartedPageSelectors.importWallet).click()

cy.get(onboardingPage.AnalyticsPageSelectors.optOut).click()

// Secret Recovery Phrase Page
// await confirmSecretRecoveryPhrase(page, seedPhrase)
// await createPassword(page, password)

cy.get(onboardingPage.WalletCreationSuccessPageSelectors.confirmButton).click()

cy.get(onboardingPage.PinExtensionPageSelectors.nextButton).click()
cy.get(onboardingPage.PinExtensionPageSelectors.confirmButton).click()

// closePopover(page)

// verifyImportedWallet(page)
}

// Checks if the wallet was imported successfully.
// On rare occasions, the MetaMask hangs during the onboarding process.
async function verifyImportedWallet(page: Page) {
Fixed Show fixed Hide fixed
const accountAddress = await cy.get(homePage.copyAccountAddressButton).textContent()

assert.strictEqual(
accountAddress?.startsWith('0x'),
true,
new Error(
[
`Incorrect state after importing the seed phrase. Account address is expected to start with "0x", but got "${accountAddress}" instead.`,
'Note: Try to re-run the cache creation. This is a known but rare error where MetaMask hangs during the onboarding process. If it persists, please file an issue on GitHub.'
].join('\n')
)
)
}
23 changes: 23 additions & 0 deletions wallets/metamask/src/cypress/support/setupMetaMaskWallet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { type BrowserContext, chromium, type Page } from '@playwright/test'
import { importWallet } from '../../playwright/pages/OnboardingPage/actions'

const SEED_PHRASE = 'test test test test test test test test test test test junk'

export default async function setupMetaMaskWallet(port: number) {
const debuggerDetails = await fetch(`http://127.0.0.1:${port}/json/version`)

const debuggerDetailsConfig = (await debuggerDetails.json()) as {
webSocketDebuggerUrl: string
}

const browser = await chromium.connectOverCDP(debuggerDetailsConfig.webSocketDebuggerUrl)

const context = browser.contexts()[0] as BrowserContext

// First page (index equal 0) is the cypress page, second one (index equal 1) is the extension page
const extensionPage = context.pages()[1] as Page

await importWallet(extensionPage, SEED_PHRASE, 'password')

await extensionPage.close()
}
77 changes: 77 additions & 0 deletions wallets/metamask/src/cypress/support/synpressCommands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/// <reference types="cypress" />
// ***********************************************
// This example commands.ts shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************

// import type { Network } from '../../type/Network'
// import type { WalletMock } from '../../type/WalletMock'
declare global {
namespace Cypress {
interface Chainable {

importWallet(seedPhrase: string): Chainable<void>
// importWalletFromPrivateKey(privateKey: `0x${string}`): Chainable<void>
// addNewAccount(): Chainable<void>
// getAllAccounts(): Chainable<Array<`0x${string}`>>
// getAccountAddress(): Chainable<`0x${string}`>
// switchAccount(accountAddress: string): Chainable<void>
// addNetwork(network: Network): Chainable<void>
// switchNetwork(networkName: string): Chainable<void>
// connectToDapp(wallet?: WalletMock): Chainable<void>
}
}
}

export default function synpressCommands() {
// Cypress.Commands.add('importWallet', (seedPhrase) => {
// const ethereumWalletMock = getEthereumWalletMock()
// ethereumWalletMock.importWallet(seedPhrase)
// })
//
// Cypress.Commands.add('importWalletFromPrivateKey', (privateKey) => {
// const ethereumWalletMock = getEthereumWalletMock()
// ethereumWalletMock.importWalletFromPrivateKey(privateKey)
// })
//
// Cypress.Commands.add('addNewAccount', () => {
// const ethereumWalletMock = getEthereumWalletMock()
// return ethereumWalletMock.addNewAccount()
// })
//
// Cypress.Commands.add('getAllAccounts', () => {
// const ethereumWalletMock = getEthereumWalletMock()
//
// return ethereumWalletMock.getAllAccounts()
// })
//
// Cypress.Commands.add('getAccountAddress', () => {
// const ethereumWalletMock = getEthereumWalletMock()
// return ethereumWalletMock.getAccountAddress()
// })
//
// Cypress.Commands.add('switchAccount', (accountAddress) => {
// const ethereumWalletMock = getEthereumWalletMock()
// ethereumWalletMock.switchAccount(accountAddress)
// })
//
// Cypress.Commands.add('addNetwork', (network) => {
// const ethereumWalletMock = getEthereumWalletMock()
// ethereumWalletMock.addNetwork(network)
// })
//
// Cypress.Commands.add('switchNetwork', (networkName) => {
// const ethereumWalletMock = getEthereumWalletMock()
// ethereumWalletMock.switchNetwork(networkName)
// })
//
// Cypress.Commands.add('connectToDapp', (wallet) => {
// const ethereumWalletMock = getEthereumWalletMock()
// ethereumWalletMock.connectToDapp(wallet)
// })
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import path from 'node:path'
import { downloadFile, ensureCacheDirExists, unzipArchive } from '@synthetixio/synpress-cache'
import fs from 'fs-extra'

export const DEFAULT_METAMASK_VERSION = '11.9.1'
export const EXTENSION_DOWNLOAD_URL = `https://github.com/MetaMask/metamask-extension/releases/download/v${DEFAULT_METAMASK_VERSION}/metamask-chrome-${DEFAULT_METAMASK_VERSION}.zip`

export async function prepareExtension() {
const cacheDirPath = ensureCacheDirExists()
export async function prepareExtension(forceCache = true) {
let outputDir = ''
if (forceCache) {
outputDir = ensureCacheDirExists()
} else {
outputDir = path.resolve("./", 'downloads')

if (!(await fs.exists(outputDir))) {
fs.mkdirSync(outputDir)
}
}

const downloadResult = await downloadFile({
url: EXTENSION_DOWNLOAD_URL,
outputDir: cacheDirPath,
outputDir,
fileName: `metamask-chrome-${DEFAULT_METAMASK_VERSION}.zip`
})

Expand Down

This file was deleted.

Loading
Loading