Skip to content
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

Chore: TypeScript in tests #49

Merged
merged 9 commits into from
Dec 21, 2021
Merged
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
1 change: 0 additions & 1 deletion .github/workflows/typedoc.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
name: typedoc


on:
push:
branches:
Expand Down
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
# Safe Gateway TypeScript SDK

[![npm](https://img.shields.io/npm/v/@gnosis.pm/safe-react-gateway-sdk?label=%40gnosis.pm%2Fsafe-react-gateway-sdk)](https://www.npmjs.com/package/@gnosis.pm/safe-react-gateway-sdk)

A TypeScript SDK for the [Safe Gateway](https://github.com/gnosis/safe-client-gateway)

## Links
* [Gateway API docs](https://gnosis.github.io/safe-client-gateway/docs/routes/index.html)
* [SDK typedoc](https://gnosis.github.io/safe-react-gateway-sdk/modules.html#getBalances)

- [Gateway API docs](https://gnosis.github.io/safe-client-gateway/docs/routes/index.html)
- [SDK typedoc](https://gnosis.github.io/safe-react-gateway-sdk/modules.html#getBalances)

## Adding an endpoint

Endpoint types are defined in `src/types/gateway.ts`.

Each endpoint consists of:
Expand Down
4 changes: 2 additions & 2 deletions e2e/propose-transaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import config from './config'

describe('proposeTransaction tests', () => {
// Skipping this test, see https://github.com/gnosis/safe-client-gateway/issues/745
it.skip('should propose a transaction and fail', async () => {
it('should propose a transaction and fail', async () => {
const req = proposeTransaction(config.baseUrl, '4', '0x4f9BD57BCC68Bf7770429F137922B3afD23d83E7', {
to: '0x49d4450977E2c95362C13D3a31a09311E0Ea26A6',
value: '0',
Expand All @@ -20,7 +20,7 @@ describe('proposeTransaction tests', () => {
origin: null,
})
await expect(req).rejects.toThrow(
'1337: {"nonFieldErrors":["Tx with safe-tx-hash=0x98798b6d9400b25397e85eb79c444a06f93d153555c1d7fd026176f02055a824 for safe=0x4f9BD57BCC68Bf7770429F137922B3afD23d83E7 was already executed in tx-hash=0x1baa941b8696ff3b0a8831f11da243a02f028122b6298ee61e3a1c0d5eeb171a"]}',
'1337: {"nonFieldErrors":["Contract-transaction-hash=0xdf2c4db07ee705e94135d92f835cc241b1d4c20e10d481a4e445265851448cb3 does not match provided contract-tx-hash=0x98798b6d9400b25397e85eb79c444a06f93d153555c1d7fd026176f02055a824"]}',
)
})
})
14 changes: 8 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@gnosis.pm/safe-react-gateway-sdk",
"version": "2.7.4",
"version": "2.7.5",
"main": "dist/index.min.js",
"types": "dist/index.d.ts",
"files": [
Expand All @@ -16,7 +16,7 @@
"@babel/core": "^7.15.0",
"@babel/preset-env": "^7.15.0",
"@babel/preset-typescript": "^7.15.0",
"@types/jest": "^27.0.1",
"@types/jest": "^27.0.3",
"@typescript-eslint/eslint-plugin": "^4.31.0",
"@typescript-eslint/parser": "^4.31.0",
"babel-jest": "^27.2.0",
Expand All @@ -34,13 +34,15 @@
"webpack-cli": "^4.7.2"
},
"scripts": {
"lint:fix": "eslint './src/**/*.ts' --fix",
"lint": "eslint './src/**/*.ts'",
"lint:fix": "yarn lint --fix",
"types": "yarn tsc",
"start": "rm -rf dist && webpack --mode production --watch",
"build": "rm -rf dist && webpack --mode production",
"prepare": "yarn build",
"prettier": "prettier -w",
"prepublishOnly": "yarn types && yarn lint && yarn test:check && yarn build",
"prettier": "prettier -w .",
"test": "jest --watch --coverage .",
"test:check": "jest --testPathPattern=tests",
"test:ci": "jest --ci --coverage --json --watchAll=false --testLocationInResults --runInBand --testPathPattern=tests"
},
"husky": {
Expand All @@ -51,7 +53,7 @@
"lint-staged": {
"src/**/*.{js,jsx,ts,tsx}": [
"eslint --fix",
"prettier --write"
"prettier --w ."
]
}
}
10 changes: 5 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export * from './types/decoded-data'
* Get basic information about a Safe. E.g. owners, modules, version etc
*/
export function getSafeInfo(baseUrl: string, chainId: string, address: string): Promise<SafeInfo> {
return callEndpoint(baseUrl, '/v1/chains/{chainId}/safes/{address}/', { path: { chainId, address } })
return callEndpoint(baseUrl, '/v1/chains/{chainId}/safes/{address}', { path: { chainId, address } })
}

/**
Expand All @@ -32,7 +32,7 @@ export function getBalances(
currency = 'usd',
query: operations['safes_balances_list']['parameters']['query'] = {},
): Promise<SafeBalanceResponse> {
return callEndpoint(baseUrl, '/v1/chains/{chainId}/safes/{address}/balances/{currency}/', {
return callEndpoint(baseUrl, '/v1/chains/{chainId}/safes/{address}/balances/{currency}', {
path: { chainId, address, currency },
query,
})
Expand Down Expand Up @@ -61,7 +61,7 @@ export function getCollectibles(
address: string,
query: operations['safes_collectibles_list']['parameters']['query'] = {},
): Promise<SafeCollectibleResponse[]> {
return callEndpoint(baseUrl, '/v1/chains/{chainId}/safes/{address}/collectibles/', {
return callEndpoint(baseUrl, '/v1/chains/{chainId}/safes/{address}/collectibles', {
path: { chainId, address },
query,
})
Expand Down Expand Up @@ -151,7 +151,7 @@ export function getChainsConfig(
baseUrl: string,
query?: operations['chains_list']['parameters']['query'],
): Promise<ChainListResponse> {
return callEndpoint(baseUrl, '/v1/chains/', {
return callEndpoint(baseUrl, '/v1/chains', {
query,
})
}
Expand All @@ -160,7 +160,7 @@ export function getChainsConfig(
* Returns a chain config
*/
export function getChainConfig(baseUrl: string, chainId: string): Promise<ChainInfo> {
return callEndpoint(baseUrl, '/v1/chains/{chainId}/', {
return callEndpoint(baseUrl, '/v1/chains/{chainId}', {
path: { chainId: chainId },
})
}
Expand Down
10 changes: 5 additions & 5 deletions src/types/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { DecodedDataRequest, DecodedDataResponse } from './decoded-data'
import { MasterCopyReponse } from './master-copies'

export interface paths {
'/v1/chains/{chainId}/safes/{address}/': {
'/v1/chains/{chainId}/safes/{address}': {
/** Get status of the safe */
get: operations['safes_read']
parameters: {
Expand All @@ -22,7 +22,7 @@ export interface paths {
}
}
}
'/v1/chains/{chainId}/safes/{address}/balances/{currency}/': {
'/v1/chains/{chainId}/safes/{address}/balances/{currency}': {
get: operations['safes_balances_list']
parameters: {
path: {
Expand All @@ -36,7 +36,7 @@ export interface paths {
get: operations['get_supported_fiat']
parameters: null
}
'/v1/chains/{chainId}/safes/{address}/collectibles/': {
'/v1/chains/{chainId}/safes/{address}/collectibles': {
/** Get collectibles (ERC721 tokens) and information about them */
get: operations['safes_collectibles_list']
parameters: {
Expand Down Expand Up @@ -102,7 +102,7 @@ export interface paths {
}
}
}
'/v1/chains/': {
'/v1/chains': {
get: operations['chains_list']
parameters: {
query: {
Expand All @@ -112,7 +112,7 @@ export interface paths {
}
}
}
'/v1/chains/{chainId}/': {
'/v1/chains/{chainId}': {
get: operations['chains_read']
parameters: {
path: {
Expand Down
68 changes: 49 additions & 19 deletions tests/endpoint.test.js → tests/endpoint.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,64 +25,94 @@ describe('callEndpoint', () => {

it('should accept a path param', async () => {
await expect(
callEndpoint('https://safe-client.staging.gnosisdev.com', '/v1/chains/4/safe/{address}', {
path: { address: '0x123' },
callEndpoint('https://safe-client.staging.gnosisdev.com', '/v1/chains/{chainId}/safes/{address}', {
path: { chainId: '4', address: '0x123' },
}),
).resolves.toEqual({ success: true })

expect(fetchData).toHaveBeenCalledWith(
'https://safe-client.staging.gnosisdev.com/v1/chains/4/safe/0x123',
'https://safe-client.staging.gnosisdev.com/v1/chains/4/safes/0x123',
undefined,
)
})

it('should accept several path params', async () => {
await expect(
callEndpoint('https://safe-client.staging.gnosisdev.com', '/v1/chains/4/balances/{address}/{currency}', {
path: { address: '0x123', currency: 'usd' },
}),
callEndpoint(
'https://safe-client.staging.gnosisdev.com',
'/v1/chains/{chainId}/safes/{address}/balances/{currency}',
{
path: { chainId: '4', address: '0x123', currency: 'usd' },
query: {},
},
),
).resolves.toEqual({ success: true })

expect(fetchData).toHaveBeenCalledWith(
'https://safe-client.staging.gnosisdev.com/v1/chains/4/balances/0x123/usd',
'https://safe-client.staging.gnosisdev.com/v1/chains/4/safes/0x123/balances/usd',
undefined,
)
})

it('should accept query params', async () => {
await expect(
callEndpoint('https://safe-client.staging.gnosisdev.com', '/v1/chains/4/balances/{address}/{currency}', {
path: { address: '0x123', currency: 'usd' },
query: { exclude_spam: true },
}),
callEndpoint(
'https://safe-client.staging.gnosisdev.com',
'/v1/chains/{chainId}/safes/{address}/balances/{currency}',
{
path: { chainId: '4', address: '0x123', currency: 'usd' },
query: { exclude_spam: true },
},
),
).resolves.toEqual({ success: true })

expect(fetchData).toHaveBeenCalledWith(
'https://safe-client.staging.gnosisdev.com/v1/chains/4/balances/0x123/usd?exclude_spam=true',
'https://safe-client.staging.gnosisdev.com/v1/chains/4/safes/0x123/balances/usd?exclude_spam=true',
undefined,
)
})

it('should accept body', async () => {
const body = {
to: '0x123',
value: 'test',
data: null,
nonce: '1',
operation: 1,
safeTxGas: '',
baseGas: '100',
gasPrice: '1',
gasToken: '',
refundReceiver: null,
safeTxHash: '0x123',
sender: '0x123',
signature: null,
origin: null,
}

await expect(
callEndpoint('https://safe-client.staging.gnosisdev.com', '/v1/chains/4/transactions/{safe_address}/propose', {
path: { safe_address: '0x123' },
body: { test: 'test' },
}),
callEndpoint(
'https://safe-client.staging.gnosisdev.com',
'/v1/chains/{chainId}/transactions/{safe_address}/propose',
{
path: { chainId: '4', safe_address: '0x123' },
body,
},
),
).resolves.toEqual({ success: true })

expect(fetchData).toHaveBeenCalledWith(
'https://safe-client.staging.gnosisdev.com/v1/chains/4/transactions/0x123/propose',
{ test: 'test' },
body,
)
})

it('should accept a raw URL', async () => {
await expect(
callEndpoint(
'https://safe-client.staging.gnosisdev.com',
'/v1/chains/4/balances/{address}/{currency}',
{ path: { address: '0x123', currency: 'usd' }, query: { exclude_spam: true } },
'/v1/chains/{chainId}/safes/{address}/balances/{currency}',
{ path: { chainId: '4', address: '0x123', currency: 'usd' }, query: { exclude_spam: true } },
'/test-url?raw=true',
),
).resolves.toEqual({ success: true })
Expand Down
43 changes: 43 additions & 0 deletions tests/types.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import {
SafeAppData,
MultisigTransactionRequest,
BlockExplorerUriTemplate,
FiatCurrencies,
MasterCopyReponse,
DecodedDataParameterValue,
} from '../src'

describe('Types are exported from index correctly', () => {
it('Random type check', () => {
const val = {} as unknown as
| SafeAppData
| MultisigTransactionRequest
| BlockExplorerUriTemplate
| FiatCurrencies
| MasterCopyReponse
| DecodedDataParameterValue
expect(val).toBe(val)
})

it('Dynamic enum export check', () => {
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
const { default: _ = null, ...rest } = require('../src/index')
const exportedNames = Object.keys(rest)

const fs = require('fs')
const path = require('path')

const typesDir = path.join(__dirname, '..', 'src', 'types')

const exportedTypeNames = fs
.readdirSync(typesDir)
.filter((file) => file !== 'api.ts')
.flatMap((file) => {
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
const { default: _ = null, ...rest } = require(`../src/types/${file}`)
return Object.keys(rest)
})

exportedTypeNames.every((type) => expect(exportedNames.includes(type)).toBe(true))
})
})
10 changes: 6 additions & 4 deletions tests/utils.test.js → tests/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { fetchData, insertParams, stringifyQuery } from '../src/utils'

jest.mock('isomorphic-unfetch')

const fetchMock = fetch as typeof fetch & jest.Mock

describe('utils', () => {
describe('insertParams', () => {
it('should insert a param into a string', () => {
Expand Down Expand Up @@ -32,7 +34,7 @@ describe('utils', () => {

describe('fetchData', () => {
it('should fetch a simple url', async () => {
fetch.mockImplementation(() => {
fetchMock.mockImplementation(() => {
return Promise.resolve({
ok: true,
text: () => Promise.resolve('{"success": "true"}'),
Expand All @@ -45,7 +47,7 @@ describe('utils', () => {
})

it('should make a post request', async () => {
fetch.mockImplementation(() => {
fetchMock.mockImplementation(() => {
return Promise.resolve({
ok: true,
text: () => Promise.resolve('{"success": "true"}'),
Expand All @@ -65,7 +67,7 @@ describe('utils', () => {
})

it('should throw if response is not OK', async () => {
fetch.mockImplementation(() => {
fetchMock.mockImplementation(() => {
return Promise.resolve({
ok: false,
statusText: 'Failed',
Expand All @@ -78,7 +80,7 @@ describe('utils', () => {
})

it('should throw the response text for 50x errors', async () => {
fetch.mockImplementation(() => {
fetchMock.mockImplementation(() => {
return Promise.resolve({
ok: false,
statusText: 'Failed',
Expand Down
8 changes: 4 additions & 4 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1258,10 +1258,10 @@
dependencies:
"@types/istanbul-lib-report" "*"

"@types/jest@^27.0.1":
version "27.0.1"
resolved "https://registry.yarnpkg.com/@types/jest/-/jest-27.0.1.tgz#fafcc997da0135865311bb1215ba16dba6bdf4ca"
integrity sha512-HTLpVXHrY69556ozYkcq47TtQJXpcWAWfkoqz+ZGz2JnmZhzlRjprCIyFnetSy8gpDWwTTGBcRVv1J1I1vBrHw==
"@types/jest@^27.0.3":
version "27.0.3"
resolved "https://registry.yarnpkg.com/@types/jest/-/jest-27.0.3.tgz#0cf9dfe9009e467f70a342f0f94ead19842a783a"
integrity sha512-cmmwv9t7gBYt7hNKH5Spu7Kuu/DotGa+Ff+JGRKZ4db5eh8PnKS4LuebJ3YLUoyOyIHraTGyULn23YtEAm0VSg==
dependencies:
jest-diff "^27.0.0"
pretty-format "^27.0.0"
Expand Down