Add jsonrpc createClientMock
This commit is contained in:
parent
eebe26f706
commit
9199961fdb
18
packages/jsonrpc/src/createClientMock.test.ts
Normal file
18
packages/jsonrpc/src/createClientMock.test.ts
Normal 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')
|
||||||
|
})
|
||||||
|
|
||||||
|
})
|
||||||
34
packages/jsonrpc/src/createClientMock.ts
Normal file
34
packages/jsonrpc/src/createClientMock.ts
Normal 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>>,
|
||||||
|
]
|
||||||
|
}
|
||||||
@ -3,5 +3,8 @@
|
|||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"outDir": "esm"
|
"outDir": "esm"
|
||||||
},
|
},
|
||||||
"references": []
|
"references": [
|
||||||
|
{"path": "../logger/tsconfig.esm.json"},
|
||||||
|
{"path": "../redux/tsconfig.esm.json"}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,6 +6,7 @@
|
|||||||
"rootDir": "src"
|
"rootDir": "src"
|
||||||
},
|
},
|
||||||
"references": [
|
"references": [
|
||||||
{"path": "../logger"}
|
{"path": "../logger"},
|
||||||
|
{"path": "../redux"}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user