Skip to content

Commit

Permalink
fix: tests mock handler usage
Browse files Browse the repository at this point in the history
  • Loading branch information
Keyrxng committed Jun 19, 2024
1 parent 9247e58 commit 91470cc
Show file tree
Hide file tree
Showing 4 changed files with 98 additions and 70 deletions.
4 changes: 2 additions & 2 deletions src/handlers/generate-erc20-permit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export async function generateErc20PermitSignature(contextOrPayload: Context | P
adminWallet = new ethers.Wallet(privateKey, provider);
} catch (error) {
const errorMessage = `Failed to instantiate wallet: ${error}`;
_logger.debug(errorMessage);
_logger.error(errorMessage);
throw new Error(errorMessage);
}

Expand All @@ -93,7 +93,7 @@ export async function generateErc20PermitSignature(contextOrPayload: Context | P
tokenDecimals = await tokenContract.decimals();
} catch (error) {
const errorMessage = `Failed to get token decimals for token: ${tokenAddress}`;
_logger.debug(errorMessage);
_logger.error(errorMessage);
throw new Error(errorMessage);
}

Expand Down
4 changes: 4 additions & 0 deletions tests/generate-erc20-permit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import { describe, expect, it, beforeEach, jest } from "@jest/globals";
import { generateErc20PermitSignature } from "../src";
import { Context } from "../src/types/context";
import { SPENDER, mockContext, ERC20_REWARD_TOKEN_ADDRESS } from "./constants";
import { ethers } from "ethers";
jest.mock("../src/utils/get-fastest-provider", () => ({
getFastestProvider: jest.fn(() => new ethers.JsonRpcProvider("https://gnosis.drpc.org")),
}));

describe("generateErc20PermitSignature", () => {
let context: Context;
Expand Down
154 changes: 88 additions & 66 deletions tests/generate-erc721-permit.test.ts
Original file line number Diff line number Diff line change
@@ -1,79 +1,25 @@
import { MaxUint256 } from "@uniswap/permit2-sdk";
import { BaseWallet, keccak256, toUtf8Bytes, TypedDataDomain, TypedDataField } from "ethers";
import { BaseWallet, ethers, keccak256, toUtf8Bytes, TypedDataDomain, TypedDataField } from "ethers";
import { generateErc721PermitSignature } from "../src";
import { Context } from "../src/types/context";
import { Env } from "../src/types/env";
import { cypherText, mockContext, NFT_CONTRACT_ADDRESS, SPENDER } from "./constants";
import { describe, expect, it, beforeEach, afterEach, jest } from "@jest/globals";

jest.mock("../src/utils/get-fastest-provider", () => ({
getFastestProvider: jest.fn(() => new ethers.JsonRpcProvider("https://gnosis.drpc.org")),
}));

describe("generateErc721PermitSignature", () => {
let context: Context;
const userId = 123;

// cSpell: disable

jest.autoMockOn();

beforeEach(() => {
process.env.X25519_PRIVATE_KEY = "bHH4PDnwb2bsG9nmIu1KeIIX71twQHS-23wCPfKONls";
process.env.NFT_CONTRACT_ADDRESS = NFT_CONTRACT_ADDRESS;
process.env.NFT_MINTER_PRIVATE_KEY = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

context = {
...mockContext,
config: {
evmNetworkId: 100,
evmPrivateEncrypted: cypherText,
isNftRewardEnabled: true,
nftMinterPrivateKey: process.env.NFT_MINTER_PRIVATE_KEY,
nftContractAddress: NFT_CONTRACT_ADDRESS,

// possible inputs from workflow_dispatch
token: NFT_CONTRACT_ADDRESS,
amount: 100,
spender: SPENDER,
userId: 123,

// nft specific inputs
contribution_type: "contribution",
issueID: 123,
},
octokit: {
request() {
return { data: { id: 1, login: "123" } };
},
users: {
getByUsername: jest.fn().mockReturnValue({ data: { id: userId } }),
},
},
} as unknown as Context;
context.env = process.env as Env;
context.eventName = "issues.closed";
jest.mock("@supabase/supabase-js", () => {
return {
createClient: jest.fn().mockReturnValue({
from: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
eq: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
eq: jest.fn().mockReturnValue({
single: jest.fn().mockReturnValue({ id: 123 }),
}),
}),
}),
}),
}),
}),
};
});
(context.adapters.supabase.wallet.getWalletByUserId as jest.Mock).mockReturnValue(SPENDER);
(context.adapters.supabase.user.getUserIdByWallet as jest.Mock).mockReturnValue(userId);
jest
.spyOn(BaseWallet.prototype, "signTypedData")
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.mockImplementation((domain: TypedDataDomain, types: Record<string, TypedDataField[]>, value: Record<string, unknown>) => {
return Promise.resolve("0x0");
});
const { getFastestProvider } = require("../src/utils/get-fastest-provider");
getFastestProvider.mockImplementation(() => Promise.resolve(new ethers.JsonRpcProvider("https://gnosis.drpc.org")));
context = setupBeforeEach(context, userId)
});

afterEach(() => {
Expand Down Expand Up @@ -110,10 +56,6 @@ describe("generateErc721PermitSignature", () => {
expect(context.logger.error).not.toHaveBeenCalled();
});

it("should throw an error if RPC is not defined", async () => {
context.config.evmNetworkId = 123;
await expect(generateErc721PermitSignature(context, "123", "contribution")).rejects.toThrow("Failed to get fastest provider for networkId: 123");
});

it("should throw an error if NFT minter private key is not defined", async () => {
delete process.env.NFT_MINTER_PRIVATE_KEY;
Expand All @@ -139,3 +81,83 @@ describe("generateErc721PermitSignature", () => {
expect(context.logger.error).toHaveBeenCalledWith("No wallet found for user");
});
});

describe("error handling", () => {
let context: Context;
beforeEach(() => {
const { getFastestProvider } = require("../src/utils/get-fastest-provider");
getFastestProvider.mockImplementation(() => Promise.reject(new Error("Failed to get fastest provider for networkId: 123")));
context = setupBeforeEach(context, 123, false)
});

it("should throw an error if RPC is not defined", async () => {
context.config.evmNetworkId = 123;
await expect(generateErc721PermitSignature(context, "123", "contribution")).rejects.toThrow("Failed to get fastest provider for networkId: 123");
});

})

function setupBeforeEach(context: Context, userId: number, withProvider = true) {
process.env.X25519_PRIVATE_KEY = "bHH4PDnwb2bsG9nmIu1KeIIX71twQHS-23wCPfKONls";
process.env.NFT_CONTRACT_ADDRESS = NFT_CONTRACT_ADDRESS;
process.env.NFT_MINTER_PRIVATE_KEY = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

context = {
...mockContext,
config: {
evmNetworkId: 100,
evmPrivateEncrypted: cypherText,
isNftRewardEnabled: true,
nftMinterPrivateKey: process.env.NFT_MINTER_PRIVATE_KEY,
nftContractAddress: NFT_CONTRACT_ADDRESS,

// possible inputs from workflow_dispatch
token: NFT_CONTRACT_ADDRESS,
amount: 100,
spender: SPENDER,
userId: 123,

// nft specific inputs
contribution_type: "contribution",
issueID: 123,
},
octokit: {
request() {
return { data: { id: 1, login: "123" } };
},
users: {
getByUsername: jest.fn().mockReturnValue({ data: { id: userId } }),
},
},
} as unknown as Context;
context.env = process.env as Env;
context.eventName = "issues.closed";
jest.mock("@supabase/supabase-js", () => {
return {
createClient: jest.fn().mockReturnValue({
from: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
eq: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
eq: jest.fn().mockReturnValue({
single: jest.fn().mockReturnValue({ id: 123 }),
}),
}),
}),
}),
}),
}),
};
});
(context.adapters.supabase.wallet.getWalletByUserId as jest.Mock).mockReturnValue(SPENDER);
(context.adapters.supabase.user.getUserIdByWallet as jest.Mock).mockReturnValue(userId);
jest
.spyOn(BaseWallet.prototype, "signTypedData")
// eslint-disable-next-line @typescript-eslint/no-unused-vars
.mockImplementation((domain: TypedDataDomain, types: Record<string, TypedDataField[]>, value: Record<string, unknown>) => {
return Promise.resolve("0x0");
});


return context;
}
6 changes: 4 additions & 2 deletions tests/generate-payout-permit.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
// import { generateErc20PermitSignature } from "../src/handlers/generate-erc20-permit";
import { ethers } from "ethers";
import { generateErc20PermitSignature, generatePayoutPermit } from "../src";
// import { generateErc721PermitSignature } from "../src/handlers/generate-erc721-permit";
import { Context } from "../src/types/context";
import { cypherText, mockContext, SPENDER } from "./constants";
import { describe, expect, it, beforeEach, afterEach, jest } from "@jest/globals";

jest.mock("../src/handlers/generate-erc20-permit");
jest.mock("../src/handlers/generate-erc721-permit");
jest.mock("../src/utils/get-fastest-provider", () => ({
getFastestProvider: jest.fn(() => new ethers.JsonRpcProvider("https://gnosis.drpc.org")),
}));

describe("generatePayoutPermit", () => {
let context: Context;
Expand Down

0 comments on commit 91470cc

Please sign in to comment.