DePayFi / web3-mock

šŸ¤” JavaScript library to mock web3 responses either by emulating web3 wallets or web3 RPC requests.
https://depay.com
MIT License
87 stars 20 forks source link

Vitest + playwright #28

Closed damianobarbati closed 1 year ago

damianobarbati commented 1 year ago

Hey @10xSebastian , I'm using vitest (same as jest) to control playwright but it's not clear to me where I should put the mock logic.

In my vitest.setup.ts:

// web3-mock polyfills:
import xhr2 from 'xhr2';
global.XMLHttpRequest = xhr2;
global.location = { host: undefined };

In my spec:

/* eslint testing-library/prefer-screen-queries: off */
import { mock, resetMocks } from '@depay/web3-mock';
import { ethers } from 'ethers';
import { type Browser, chromium, type Page } from 'playwright';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';

beforeEach(resetMocks);
beforeEach(() => {
  mock('ethereum');
});

describe('web3', () => {
  let browser: Browser;
  let page: Page;

  beforeAll(async () => {
    browser = await chromium.launch({
      headless: !process.env.HEADED,
      slowMo: process.env.HEADED ? 2000 : undefined,
    });
    page = await browser.newPage();
  });

  afterAll(async () => {
    await browser.close();
  });

  it('should login with the current wallet', async () => {
    const signMock = mock({
      blockchain: 'ethereum',
      accounts: {
        return: ['0x4b5047f90d06BC6a47b362717687e3ee5Dfc9B1d'],
      },
    });

    await page.goto('http://localhost:3000');
    const button = page.getByText(/Connect Wallet/);
    await button.click();

    expect(signMock).toHaveBeenCalled(); // šŸ‘ˆšŸ» TypeError: [Function spy] is not a spy or a call to a spy!
  });
});
10xSebastian commented 1 year ago

Hey @damianobarbati

This test environment is disconnected from the browser. So if you mock the test environment, it will not have any effect on your JS application that runs within the browser. You would need to get the mocking into the JS environment that runs within the browser.

10xSebastian commented 1 year ago

Things you can try

https://playwright.dev/docs/api/class-browsercontext#browser-context-add-init-script

or

https://playwright.dev/docs/api/class-browsercontext#browser-context-expose-function