Automated test for Ethereum service on NestJS

Burgossrodrigo
CoinsBench
Published in
2 min readApr 30, 2024

--

The use case of this approach is to avoid breaking your app in production due to basic errors on your script. It obviously can be extended but it’s an excelent starting point.

Ethereum Service

Next we will see a very basic class in typescript with three methods:

getProvider(providerUrl: string): ethers.JsonRpcProvider

Which only returns an instance for an ethers v6 JsonRpcProvider.

async getWorkingProvider(providerUrls: string[]): Promise<ethers.JsonRpcProvider>

A bit more complex due an loop that interacts with an array of url’s and verify if any of then are responsive using asyncronous provider.getNetwork() method within the provider instance.

chooseRpcUrl(network: string): Promise<ethers.JsonRpcProvider>

This last method, also very simple is only an interaction through an enum with an switch statement to choose which chain to perform getWorkingProvider()

Test script

  describe('getWorkingProvider', () => {
it('should return a provider for the mainnet', async () => {
const provider = await service.getWorkingProvider(ETHEREUM_MAINNET_URL);
expect(provider).toBeDefined();
expect((await provider.getNetwork()).chainId).toBe(BigInt(1));
});
});

Basically we invoke the getNetwork() method from the provider (which comes in BigInt format in ethers v6) knowing that it should be 1 for ethereum mainnet and then we comparte it with the toBe method from the expect.

The same can be reproduced within the other chains:

  describe('getWorkingProvider', () => {
it('should return a provider for the mainnet', async () => {
const provider = await service.getWorkingProvider(BSC_MAINNET_URL);
expect(provider).toBeDefined();
expect((await provider.getNetwork()).chainId).toBe(BigInt(56));
});
})

The output from the test should be like this:

 PASS  src/ethereum/ethereum.service.spec.ts (11.012 s)
EthereumService
√ should be defined (47 ms)
chooseRpcUrl
√ should return a provider for the mainnet (235 ms)
getWorkingProvider
√ should return a provider for the mainnet (159 ms)
√ should return a provider for the mainnet (953 ms)

The whole code (service and test):

--

--