1

I'm looking for guidance on how to best stub the win.injectedWeb3 object that's usually created by Polkadot{.js}. This is so that I can write some automated tests for a dApp frontend in Cypress w/ typescript (and then automatically sign transactions etc).

It seems like I need to utilize injectExtension from @polkadot/extension-inject but currently struggling to implement it properly to use a stub.

I'm sure other dApp builders wanting to add some UI automation have encountered this same challenge so wondered if a recommend approach already existed?

Welcoming any suggestions or pointers in the right direction, thanks in advance 🙏

1 Answer 1

1

It sounds like you are trying to stub the win.injectedWeb3 object in order to write automated tests for your dApp frontend in Cypress with TypeScript. One option to achieve this is to use the @polkadot/extension-inject library to inject a custom provider into the win.injectedWeb3 object.

Here's an example of how you can use @polkadot/extension-inject to inject a custom provider:

import { injectExtension } from '@polkadot/extension-inject';

// Define a custom provider
class CustomProvider {
  // Implement the required methods of the provider interface
  public async send(method: string, params: any[]): Promise<any> {
    // ...
  }

  public async sendAsync(method: string, params: any[]): Promise<any> {
    // ...
  }
}

// Inject the custom provider into the global `window.injectedWeb3` object
await injectExtension(new CustomProvider());```

You can use this code to inject the custom provider before running your automated tests. This way, when your dApp frontend tries to access win.injectedWeb3, it will receive the injected provider instead of the real provider.

To create a stub for the CustomProvider class, you can use a mocking library such as sinon.js or jest. Here's an example of how to use sinon.js to create a stub for the CustomProvider class:

import sinon from 'sinon';
import { injectExtension } from '@polkadot/extension-inject';

// Define a stub for the CustomProvider class
const providerStub = sinon.createStubInstance(CustomProvider);

// Inject the stub into the global `window.injectedWeb3` object
await injectExtension(providerStub);

This code creates a stub for the CustomProvider class using sinon.createStubInstance(). You can then inject the stub into the win.injectedWeb3 object using injectExtension(). This way, when your dApp frontend tries to interact with win.injectedWeb3, it will receive the stubbed provider instead of the real provider.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.