Add jsonrpc createClientMock

This commit is contained in:
Jerko Steiner 2019-09-10 21:29:10 +07:00
parent eebe26f706
commit 9199961fdb
4 changed files with 58 additions and 2 deletions

View File

@ -0,0 +1,18 @@
import createClientMock from './createClientMock'
describe('createClientMock', () => {
interface IService {
add(a: number, b: number): number
concat(a: string, b: string): string
}
it('creates a mock for all methods', async () => {
const [client, mock] = createClientMock<IService>(['add', 'concat'])
mock.add.mockReturnValue(Promise.resolve(3))
mock.concat.mockImplementation((a, b) => Promise.resolve(a + b))
expect(await client.add(4, 5)).toBe(3)
expect(await client.concat('a', 'b')).toBe('ab')
})
})

View File

@ -0,0 +1,34 @@
import { FunctionPropertyNames, TAsyncified } from './types'
export type TMocked<T> = {
[K in keyof T]:
T[K] extends (...args: infer A) => infer R
? jest.Mock<R, A>
: never
}
/**
* Creates an object with methods mocked using jest. This methods should not
* be exported in this module because it adds a dependency to jest, which is
* a dev dependency.
*
* During tests, users should require this method by writing:
*
* import createClientMock from '@rondo.dev/jsonrpc/lib/createClientMock'
*
* @private
*/
export default function createClientMock<T extends object>(
methods: Array<FunctionPropertyNames<T>>,
): [TAsyncified<T>, TMocked<TAsyncified<T>>] {
const client = methods
.reduce((obj, prop) => {
obj[prop] = jest.fn()
return obj
}, {} as any)
return [
client as TAsyncified<T>,
client as TMocked<TAsyncified<T>>,
]
}

View File

@ -3,5 +3,8 @@
"compilerOptions": {
"outDir": "esm"
},
"references": []
"references": [
{"path": "../logger/tsconfig.esm.json"},
{"path": "../redux/tsconfig.esm.json"}
]
}

View File

@ -6,6 +6,7 @@
"rootDir": "src"
},
"references": [
{"path": "../logger"}
{"path": "../logger"},
{"path": "../redux"}
]
}