jest-mock-proxy

Mock classes and objects with the power of proxies!
Creates a Proxy
that will dynamically create spies when a property is accessed the first time.
Every subsequent access will use the same spy. In combination with TypeScript this allows us to create a mock for any class/object without having to specify all its properties and methods.
tl;dr;
- The
Proxy
makes any property and method available on the mock at runtime.
- TypeScript limits access to properties and methods to the specified generic.
Install
Requires node 8+.
$ yarn add -D jest-mock-proxy
or
$ npm install -D jest-mock-proxy
Usage
Mock objects and instances
export class Service {
foo() {
console.log('hello');
}
bar(s: string) {
return s;
}
}
import { createMockProxy } from 'jest-mock-proxy';
import { service } from './service';
const mock = createMockProxy<typeof Service>();
mock.foo();
mock.bar.mockReturnValue('some string');
mock.bar('test');
Example: Mock an elastic search client.
import { Client } from 'elasticsearch';
import { createMockProxy } from 'jest-mock-proxy';
import fixture from './__fixtures__/elastic-response.json';
import createService from './createService';
const client = createMockProxy<Client>();
const service = createService(client);
beforeEach(() => {
client.mockClear();
client.search.mockResolvedValue(fixture);
});
test('use service to query', async () => {
await service.query('https://example.com?q=hello');
expect(client.search.mock.calls).toMatchSnapshot();
});
Mock a class and use jest's automock
When you need to mock a dependency via jest.mock
, because you have no access to the module.
import { Pool, PoolConfig } from 'pg';
const pool = new Pool();
export const query = async (q: string, values?: any[]) => {
const { rows } = pool.query(q, values);
return rows;
};
import { Pool } from 'pg';
import { createProxyFromMock } from 'jest-mock-proxy';
import { query } from './query';
jest.mock('pg');
const mockedPool = createProxyFromMock(Pool);
test('you can now mock the pool.query', async () => {
mockedPool.query.mockResolvedValue({ rows: [{ id: 1, data: 'data' }] });
await query('SELECT * FROM table1');
});
3.1.2 (2022-05-19)
Tooling
[object Object]## 3.1.1 (2022-05-19)
Refactoring & Improvements
- Add option to name a mock (ca1f639)
Tooling
Documentation
Miscellaneous
- Name the mock functions (#3) (ab14878), closes [#3](https://github.com/sebald/jest-mock-proxy/issues/Name the mock functions (#3/
[object Object]# 3.0.0 (2019-03-22)
Features
- Introduce
createProxyFromMock
(#2) (cfdd310), closes [#2](https://github.com/sebald/jest-mock-proxy/issues/⨠Introduce createProxyFromMock
(#2/
Tooling
Documentation
Miscellaneous
[object Object]