Skip to content

Commit

Permalink
🤓 Add first jest test w/network mock (#211)
Browse files Browse the repository at this point in the history
* 🤓 Add first network mock

* Improve test w/zod validation
  • Loading branch information
dawsbot committed Apr 21, 2023
1 parent 81036f5 commit 9b8df51
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
34 changes: 24 additions & 10 deletions src/providers/test/json-rpc-provider/get-gas-price.test.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,33 @@
import { ethers } from 'ethers';
import unfetch from 'isomorphic-unfetch';
import z from 'zod';
import { JsonRpcProvider } from '../../../index';
import { mockOf } from '../mock-of';
import { rpcUrls } from '../rpc-urls';
import { TinyBig } from './../../../shared/tiny-big/tiny-big';

jest.mock('isomorphic-unfetch');
const postResponse = JSON.stringify({
jsonrpc: '2.0',
id: 1,
result: '0xa',
});

const rpcUrl = rpcUrls.mainnet;

describe('provider.getGasPrice', () => {
it('should match ethers and essential-eth', async () => {
const ethersProvider = new ethers.providers.StaticJsonRpcProvider(rpcUrl);
const essentialEthProvider = new JsonRpcProvider(rpcUrl);
const [ethersGasPrice, essentialEthGasPrice] = await Promise.all([
ethersProvider.getGasPrice(),
essentialEthProvider.getGasPrice(),
]);
it('should get integer of gas price', async () => {
const provider = new JsonRpcProvider(rpcUrl);
mockOf(unfetch).mockReturnValueOnce(
Promise.resolve({
text: () => postResponse,
} as unknown as Response),
);

const gasPrice = await provider.getGasPrice();
expect(z.instanceof(TinyBig).safeParse(gasPrice).success).toBe(true);
expect(
ethersGasPrice.sub(essentialEthGasPrice.toString()).toNumber(),
).toBeLessThan(100);
z.number().int().positive().safeParse(gasPrice.toNumber()).success,
).toBe(true);
expect(gasPrice.toString()).toBe('10');
});
});
18 changes: 18 additions & 0 deletions src/providers/test/mock-of.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* Helper function for mocking other functions.
*
* Import it using this:
* ```ts
* import { mockOf } from '@earnifi/shared/src/utils/testing/mock-of';
* ```
*
* @param fn
* @example mockOf(stripe.checkout.sessions.create).mockResolvedValue(mockSession);
* @see https://twitter.com/scastiel/status/1631354119192473601?s=20
*/
export const mockOf = <
FunctionParameters extends unknown[],
FunctionReturnType,
>(
fn: (...args: FunctionParameters) => FunctionReturnType,
) => fn as jest.Mock<FunctionReturnType, FunctionParameters>;

0 comments on commit 9b8df51

Please sign in to comment.