@yoroi/api
Version:
The API package of Yoroi SDK
82 lines (69 loc) • 3.11 kB
text/typescript
import axios from 'axios'
import {getProtocolParams, isProtocolParamsResponse} from './protocol-params'
import {protocolParamsMockResponse} from './protocol-params.mocks'
jest.mock('axios')
const mockedAxios = axios as jest.MockedFunction<typeof axios>
describe('getProtocolParams', () => {
const baseUrl = 'https://localhost'
const mockFetch = jest.fn()
const customFetcher = jest.fn().mockResolvedValue(protocolParamsMockResponse)
beforeEach(() => {
jest.clearAllMocks()
mockedAxios.mockReset && mockedAxios.mockReset()
})
it('returns parsed data when response is valid', async () => {
mockFetch.mockResolvedValue(protocolParamsMockResponse)
const protocolParams = getProtocolParams(baseUrl, mockFetch)
const result = await protocolParams()
expect(result).toEqual(protocolParamsMockResponse)
})
it('throws an error if response is not valid', async () => {
mockFetch.mockResolvedValue(null)
const protocolParams = getProtocolParams(baseUrl, mockFetch)
await expect(protocolParams()).rejects.toThrow(
'Invalid protocol params response',
)
})
it('rejects when response data fails validation', async () => {
const invalidResponse = {unexpectedField: 'invalid data'}
mockFetch.mockResolvedValue(invalidResponse)
const protocolParams = getProtocolParams('https://localhost', mockFetch)
await expect(protocolParams()).rejects.toThrow(
'Invalid protocol params response',
)
})
it('uses a custom fetcher function', async () => {
const protocolParams = getProtocolParams(baseUrl, customFetcher)
const result = await protocolParams()
expect(customFetcher).toHaveBeenCalled()
expect(result).toEqual(protocolParamsMockResponse)
const pp = getProtocolParams(baseUrl)
expect(pp).toBeDefined()
})
it('uses fetcher and returns data on successful fetch', async () => {
const fetcher = jest.fn().mockResolvedValue(protocolParamsMockResponse)
const protocolParams = getProtocolParams(baseUrl, fetcher)
const result = await protocolParams()
expect(fetcher).toHaveBeenCalled()
expect(result).toEqual(protocolParamsMockResponse)
})
it('throws an error on network issues', async () => {
const networkError = new Error('Network Error')
mockFetch.mockRejectedValue(networkError)
const protocolParams = getProtocolParams(baseUrl, mockFetch)
await expect(protocolParams()).rejects.toThrow(networkError.message)
})
})
describe('isProtocolParamsResponse', () => {
it('returns true for a valid protocol parameters response', () => {
expect(isProtocolParamsResponse(protocolParamsMockResponse)).toBe(true)
})
it('returns false for an invalid protocol parameters response', () => {
const invalidResponse = {...protocolParamsMockResponse, epoch: 'invalid'}
expect(isProtocolParamsResponse(invalidResponse)).toBe(false)
})
it('returns false for an incomplete protocol parameters response', () => {
const incompleteResponse = {min_fee_a: 44, min_fee_b: 155381}
expect(isProtocolParamsResponse(incompleteResponse)).toBe(false)
})
})