Giter VIP home page Giter VIP logo

jest-mock-proxy's Introduction

jest-mock-proxy

buid buid version MIT License

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;

  1. The Proxy makes any property and method available on the mock at runtime.
  2. 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

// service.ts
export class Service {
  foo() {
    console.log('hello');
  }
  bar(s: string) {
    return s;
  }
}

// some.test.ts
import { createMockProxy } from 'jest-mock-proxy';
import { service } from './service';

const mock = createMockProxy<Service>();

mock.foo();

mock.bar.mockReturnValue('some string');
mock.bar('test'); // 'some string'

Example: Mock an elastic search client.

import { Client } from 'elasticsearch';
import { createMockProxy } from 'jest-mock-proxy';
import fixture from './__fixtures__/elastic-response.json';

// This is an imaginary service that depends on the elastic search client.
import createService from './createService';

const client = createMockProxy<Client>();
cosnt 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.

// query.ts
import { Pool, PoolConfig } from 'pg';

// ๐Ÿ˜จ This makes testing hard...
const pool = new Pool();

export const query = async (q: string, values?: any[]) => {
  // ...because how to mock this?
  const { rows } = pool.query(q, values);
  return rows;
};

// query.test.ts
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 () => {
  // Use mockedPool so you get good type inference from TS
  mockedPool.query.mockResolvedValue({ rows: [{ id: 1, data: 'data' }] });

  await query('SELECT * FROM table1'); // returns `[{ id: 1, data: 'data' }]`
});

jest-mock-proxy's People

Contributors

sebald avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.