Skip to content

chore: migrate tests to vitest #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/client/.npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ tsconfig.build.json
babel.config.js
release.sh

# Jest
jest.setup.ts
jest.config.ts
coverage/**
# Vitest
vitest.config.ts
vitest.setup.ts
coverage/**
61 changes: 0 additions & 61 deletions packages/client/jest.config.ts

This file was deleted.

25 changes: 0 additions & 25 deletions packages/client/jest.setup.ts

This file was deleted.

13 changes: 4 additions & 9 deletions packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
"author": "Coinbase, Inc.",
"license": "Apache-2.0",
"scripts": {
"test": "jest",
"test:coverage": "yarn test:unit && open coverage/lcov-report/index.html",
"test": "vitest",
"test:coverage": "vitest run --coverage && open coverage/index.html",
"prebuild": "rm -rf ./dist && node -p \"'export const LIB_VERSION = \\'' + require('./package.json').version + '\\';'\" > src/version.ts",
"build": "tsc -p ./tsconfig.build.json && tsc-alias",
"dev": "tsc --watch & nodemon --watch dist --delay 1 --exec tsc-alias",
Expand Down Expand Up @@ -53,15 +53,13 @@
"@babel/preset-typescript": "^7.22.5",
"@peculiar/webcrypto": "^1.4.3",
"@react-native-async-storage/async-storage": "^1.24.0",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "14.3.1",
"@types/jest": "^27.5.2",
"@types/node": "^14.18.54",
"@types/react": "^18.0.25",
"@types/react-native": "^0.70.6",
"@typescript-eslint/eslint-plugin": "^6.2.0",
"@typescript-eslint/parser": "^6.2.0",
"babel-jest": "^27.5.1",
"@vitest/coverage-v8": "^3.0.8",
"eslint": "^8.45.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-prettier": "^5.0.0",
Expand All @@ -71,12 +69,9 @@
"eslint-plugin-simple-import-sort": "^10.0.0",
"eslint-plugin-unused-imports": "^3.0.0",
"expo-web-browser": "^13.0.3",
"jest": "^27.5.1",
"jest-chrome": "^0.7.2",
"jest-websocket-mock": "^2.4.0",
"jsdom": "^26.0.0",
"nodemon": "^3.1.0",
"prettier": "^3.0.0",
"ts-jest": "^27.1.5",
"ts-node": "^10.9.1",
"tsc-alias": "^1.8.8",
"tslib": "^2.6.0",
Expand Down
86 changes: 43 additions & 43 deletions packages/client/src/MWPClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,30 +16,30 @@ import { ScopedAsyncStorage } from ':core/storage/ScopedAsyncStorage';
import { fetchRPCRequest } from ':core/util/utils';
import { Wallets } from ':core/wallet';

jest.mock(':core/util/utils', () => {
const actual = jest.requireActual(':core/util/utils');
vi.mock(':core/util/utils', async () => {
const actual = await vi.importActual(':core/util/utils');
return {
...actual,
fetchRPCRequest: jest.fn(),
fetchRPCRequest: vi.fn(),
};
});

jest.mock('./components/communication/postRequestToWallet');
vi.mock('./components/communication/postRequestToWallet');

jest.mock('expo-web-browser', () => ({
openAuthSessionAsync: jest.fn(),
dismissBrowser: jest.fn(),
vi.mock('expo-web-browser', () => ({
openAuthSessionAsync: vi.fn(),
dismissBrowser: vi.fn(),
}));

jest.mock('./components/key/KeyManager');
const storageStoreSpy = jest.spyOn(ScopedAsyncStorage.prototype, 'storeObject');
const storageClearSpy = jest.spyOn(ScopedAsyncStorage.prototype, 'clear');
vi.mock('./components/key/KeyManager');
const storageStoreSpy = vi.spyOn(ScopedAsyncStorage.prototype, 'storeObject');
const storageClearSpy = vi.spyOn(ScopedAsyncStorage.prototype, 'clear');

jest.mock(':core/cipher/cipher', () => ({
decryptContent: jest.fn(),
encryptContent: jest.fn(),
exportKeyToHexString: jest.fn(),
importKeyFromHexString: jest.fn(),
vi.mock(':core/cipher/cipher', () => ({
decryptContent: vi.fn(),
encryptContent: vi.fn(),
exportKeyToHexString: vi.fn(),
importKeyFromHexString: vi.fn(),
}));

const mockCryptoKey = {} as CryptoKey;
Expand All @@ -64,7 +64,7 @@ const mockWallet = Wallets.CoinbaseSmartWallet;
describe('MWPClient', () => {
let client: MWPClient;
let mockMetadata: AppMetadata;
let mockKeyManager: jest.Mocked<KeyManager>;
let mockKeyManager: ReturnType<typeof vi.mocked<KeyManager>>;

beforeEach(async () => {
mockMetadata = {
Expand All @@ -73,18 +73,18 @@ describe('MWPClient', () => {
customScheme: 'myapp://',
};

(postRequestToWallet as jest.Mock).mockResolvedValue(mockSuccessResponse);
(postRequestToWallet as ReturnType<typeof vi.fn>).mockResolvedValue(mockSuccessResponse);

mockKeyManager = new KeyManager({
wallet: mockWallet,
}) as jest.Mocked<KeyManager>;
(KeyManager as jest.Mock).mockImplementation(() => mockKeyManager);
}) as ReturnType<typeof vi.mocked<KeyManager>>;
(KeyManager as ReturnType<typeof vi.fn>).mockImplementation(() => mockKeyManager);
storageStoreSpy.mockReset();

(importKeyFromHexString as jest.Mock).mockResolvedValue(mockCryptoKey);
(exportKeyToHexString as jest.Mock).mockResolvedValueOnce('0xPublicKey');
(importKeyFromHexString as ReturnType<typeof vi.fn>).mockResolvedValue(mockCryptoKey);
(exportKeyToHexString as ReturnType<typeof vi.fn>).mockResolvedValueOnce('0xPublicKey');
mockKeyManager.getSharedSecret.mockResolvedValue(mockCryptoKey);
(encryptContent as jest.Mock).mockResolvedValueOnce(encryptedData);
(encryptContent as ReturnType<typeof vi.fn>).mockResolvedValueOnce(encryptedData);

client = await MWPClient.createInstance({
metadata: mockMetadata,
Expand All @@ -106,8 +106,21 @@ describe('MWPClient', () => {
});

describe('handshake', () => {
it('should throw an error if failure in response.content', async () => {
const mockResponse: RPCResponseMessage = {
id: '1-2-3-4-5',
requestId: '1-2-3-4-5-6',
sender: '0xPublicKey',
content: { failure: mockError },
timestamp: new Date(),
};
(postRequestToWallet as ReturnType<typeof vi.fn>).mockResolvedValue(mockResponse);

await expect(client.handshake()).rejects.toThrowError(mockError);
});

it('should perform a successful handshake', async () => {
(decryptContent as jest.Mock).mockResolvedValueOnce({
(decryptContent as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
result: {
value: ['0xAddress'],
},
Expand All @@ -130,26 +143,13 @@ describe('MWPClient', () => {
expect(storageStoreSpy).toHaveBeenCalledWith('walletCapabilities', mockCapabilities);
expect(storageStoreSpy).toHaveBeenCalledWith('accounts', ['0xAddress']);

expect(client.request({ method: 'eth_requestAccounts' })).resolves.toEqual(['0xAddress']);
});

it('should throw an error if failure in response.content', async () => {
const mockResponse: RPCResponseMessage = {
id: '1-2-3-4-5',
requestId: '1-2-3-4-5',
sender: '0xPublicKey',
content: { failure: mockError },
timestamp: new Date(),
};
(postRequestToWallet as jest.Mock).mockResolvedValue(mockResponse);

await expect(client.handshake()).rejects.toThrowError(mockError);
await expect(client.request({ method: 'eth_requestAccounts' })).resolves.toEqual(['0xAddress']);
});
});

describe('request', () => {
beforeAll(() => {
jest.spyOn(ScopedAsyncStorage.prototype, 'loadObject').mockImplementation(async (key) => {
vi.spyOn(ScopedAsyncStorage.prototype, 'loadObject').mockImplementation(async (key) => {
switch (key) {
case 'accounts':
return ['0xAddress'];
Expand All @@ -162,7 +162,7 @@ describe('MWPClient', () => {
});

afterAll(() => {
jest.spyOn(ScopedAsyncStorage.prototype, 'loadObject').mockRestore();
vi.mocked(ScopedAsyncStorage.prototype.loadObject).mockRestore();
});

it('should perform a successful request', async () => {
Expand All @@ -171,7 +171,7 @@ describe('MWPClient', () => {
params: ['0xMessage', '0xAddress'],
};

(decryptContent as jest.Mock).mockResolvedValueOnce({
(decryptContent as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
result: {
value: '0xSignature',
},
Expand Down Expand Up @@ -212,7 +212,7 @@ describe('MWPClient', () => {
params: [],
};

(decryptContent as jest.Mock).mockResolvedValueOnce({
(decryptContent as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
result: {
value: '0xSignature',
},
Expand Down Expand Up @@ -252,7 +252,7 @@ describe('MWPClient', () => {
params: ['0xMessage', '0xAddress'],
};

(decryptContent as jest.Mock).mockResolvedValueOnce({
(decryptContent as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
result: {
error: mockError,
},
Expand All @@ -267,7 +267,7 @@ describe('MWPClient', () => {
params: [{ chainId: '0x1' }],
};

(decryptContent as jest.Mock).mockResolvedValueOnce({
(decryptContent as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
result: {
value: null,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import { decodeResponseURLParams, encodeRequestURLParams } from './utils/encodin
import { RPCRequestMessage, RPCResponseMessage } from ':core/message';
import { Wallet } from ':core/wallet';

jest.mock('expo-web-browser', () => ({
openAuthSessionAsync: jest.fn(),
dismissBrowser: jest.fn(),
vi.mock('expo-web-browser', () => ({
openAuthSessionAsync: vi.fn(),
dismissBrowser: vi.fn(),
}));

jest.mock('./utils/encoding', () => ({
...jest.requireActual('./utils/encoding'),
decodeResponseURLParams: jest.fn(),
vi.mock('./utils/encoding', () => ({
decodeResponseURLParams: vi.fn(),
encodeRequestURLParams: vi.fn(),
}));

const mockAppCustomScheme = 'myapp://';
Expand Down Expand Up @@ -48,17 +48,18 @@ describe('postRequestToWallet', () => {

beforeEach(() => {
requestUrl = new URL(mockWalletScheme);
(encodeRequestURLParams as ReturnType<typeof vi.fn>).mockReturnValue('mocked-search-params');
requestUrl.search = encodeRequestURLParams(mockRequest);
jest.clearAllMocks();
vi.clearAllMocks();
});

it('should successfully post request to a web-based wallet', async () => {
const webWallet: Wallet = { type: 'web', scheme: mockWalletScheme } as Wallet;
(WebBrowser.openAuthSessionAsync as jest.Mock).mockResolvedValue({
(WebBrowser.openAuthSessionAsync as ReturnType<typeof vi.fn>).mockResolvedValue({
type: 'success',
url: 'https://example.com/response',
});
(decodeResponseURLParams as jest.Mock).mockResolvedValue(mockResponse);
(decodeResponseURLParams as ReturnType<typeof vi.fn>).mockResolvedValue(mockResponse);

const result = await postRequestToWallet(mockRequest, mockAppCustomScheme, webWallet);

Expand All @@ -74,7 +75,7 @@ describe('postRequestToWallet', () => {

it('should throw an error if the user cancels the request', async () => {
const webWallet: Wallet = { type: 'web', scheme: mockWalletScheme } as Wallet;
(WebBrowser.openAuthSessionAsync as jest.Mock).mockResolvedValue({
(WebBrowser.openAuthSessionAsync as ReturnType<typeof vi.fn>).mockResolvedValue({
type: 'cancel',
});

Expand Down Expand Up @@ -105,7 +106,7 @@ describe('postRequestToWallet', () => {
it('should pass through any errors from WebBrowser', async () => {
const webWallet: Wallet = { type: 'web', scheme: mockWalletScheme } as Wallet;
const mockError = new Error('Communication error');
(WebBrowser.openAuthSessionAsync as jest.Mock).mockRejectedValue(mockError);
(WebBrowser.openAuthSessionAsync as ReturnType<typeof vi.fn>).mockRejectedValue(mockError);

await expect(postRequestToWallet(mockRequest, mockAppCustomScheme, webWallet)).rejects.toThrow(
'User rejected the request'
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/core/type/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ describe('util', () => {
document.head.innerHTML = `
<link rel="shortcut icon" sizes="16x16 24x24" href="/favicon.ico">
`;
expect(getFavicon()).toEqual('http://localhost/favicon.ico');
expect(getFavicon()).toEqual('http://localhost:3000/favicon.ico');
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not entirely sure if this is acceptable, but in the vitest environment window.location.host includes the port whereas in the jest environment it does not

});
});
});
Loading
Loading