All Projects → marchaos → Jest Mock Extended

marchaos / Jest Mock Extended

Licence: mit
Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Jest Mock Extended

Mimic
Seamless client side mocking
Stars: ✭ 380 (+69.64%)
Mutual labels:  mock, mocking-framework
Pclmock
A simple mocking framework in a PCL.
Stars: ✭ 40 (-82.14%)
Mutual labels:  mock, mocking-framework
Mockk
mocking library for Kotlin
Stars: ✭ 4,214 (+1781.25%)
Mutual labels:  mock, mocking-framework
automock
A library for testing classes with auto mocking capabilities using jest-mock-extended
Stars: ✭ 26 (-88.39%)
Mutual labels:  mock, jest
Mockito
Most popular Mocking framework for unit tests written in Java
Stars: ✭ 12,453 (+5459.38%)
Mutual labels:  mock, mocking-framework
amoss
Amoss - Apex Mock Objects, Spies and Stubs - A Simple Mocking framework for Apex (Salesforce)
Stars: ✭ 55 (-75.45%)
Mutual labels:  mock, mocking-framework
Msw
Seamless REST/GraphQL API mocking library for browser and Node.js.
Stars: ✭ 7,830 (+3395.54%)
Mutual labels:  mock, mocking-framework
umock-c
A pure C mocking library
Stars: ✭ 29 (-87.05%)
Mutual labels:  mock, mocking-framework
React Nativeish
React Native / React Native Web Boilerplate
Stars: ✭ 106 (-52.68%)
Mutual labels:  jest, mock
Logginginterceptor
An OkHttp interceptor which has pretty logger for request and response. +Mock support
Stars: ✭ 1,149 (+412.95%)
Mutual labels:  mock, mocking-framework
Pegomock
Pegomock is a powerful, yet simple mocking framework for the Go programming language
Stars: ✭ 215 (-4.02%)
Mutual labels:  mock, mocking-framework
Fake Xrm Easy
The testing framework for Dynamics CRM and Dynamics 365 which runs on an In-Memory context and deals with mocks or fakes for you
Stars: ✭ 216 (-3.57%)
Mutual labels:  mock, mocking-framework
jest-launchdarkly-mock
Easily unit test LaunchDarkly feature flagged components with jest
Stars: ✭ 14 (-93.75%)
Mutual labels:  mock, jest
Mockolo
Efficient Mock Generator for Swift
Stars: ✭ 327 (+45.98%)
Mutual labels:  mock, mocking-framework
jest-how-do-i-mock-x
Runnable examples for common testing situations that often prove challenging
Stars: ✭ 63 (-71.87%)
Mutual labels:  mock, jest
Kakapo.js
🐦 Next generation mocking framework in Javascript
Stars: ✭ 535 (+138.84%)
Mutual labels:  mock, mocking-framework
mocat
🐈 Mocat is a mocking toolbar that allows you to interactively develop and test network requests.
Stars: ✭ 27 (-87.95%)
Mutual labels:  mock, mocking-framework
IOS-CoreBluetooth-Mock
Mocking library for CoreBluetooth framework.
Stars: ✭ 142 (-36.61%)
Mutual labels:  mock, mocking-framework
Graphql Query Test Mock
Easily mock GraphQL queries in your Relay Modern / Apollo / any-other-GraphQL-client tests.
Stars: ✭ 49 (-78.12%)
Mutual labels:  jest, mock
Jest Canvas Mock
🌗 A module used to mock canvas in Jest.
Stars: ✭ 189 (-15.62%)
Mutual labels:  jest, mock

jest-mock-extended

Type safe mocking extensions for Jest 🃏

Build Status Coverage Status npm version License: MIT npm downloads

Features

  • Provides complete Typescript type safety for interfaces, argument types and return types
  • Ability to mock any interface or object
  • calledWith() extension to provide argument specific expectations, which works for objects and functions.
  • Extensive Matcher API compatible with Jasmine matchers
  • Supports mocking deep objects / class instances.
  • Familiar Jest like API

Installation

npm install jest-mock-extended --save-dev

or

yarn add jest-mock-extended --dev

Example

import { mock } from 'jest-mock-extended';

interface PartyProvider {
   getPartyType: () => string;
   getSongs: (type: string) => string[]
   start: (type: string) => void;
}

describe('Party Tests', () => {
   test('Mock out an interface', () => {
       const mock = mock<PartyProvider>();
       mock.start('disco party');
       
       expect(mock.start).toHaveBeenCalledWith('disco party');
   });
   
   
   test('mock out a return type', () => {
       const mock = mock<PartyProvider>();
       mock.getPartyType.mockReturnValue('west coast party');
       
       expect(mock.getPartyType()).toBe('west coast party');
   });
});

Assigning Mocks with a Type

If you wish to assign a mock to a variable that requires a type in your test, then you should use the MockProxy<> type given that this will provide the apis for calledWith() and other built-in jest types for providing test functionality.

import { MockProxy, mock } from 'jest-mock-extended';

describe('test', () => {
    let myMock: MockProxy<MyInterface>;

    beforeEach(() => {
        myMock = mock<MyInterface>();
    })

    test(() => {
         myMock.calledWith(1).mockReturnValue(2);
         ...
    })
});

calledWith() Extension

jest-mock-extended allows for invocation matching expectations. Types of arguments, even when using matchers are type checked.

const provider = mock<PartyProvider>();
provider.getSongs.calledWith('disco party').mockReturnValue(['Dance the night away', 'Stayin Alive']);
expect(provider.getSongs('disco party')).toEqual(['Dance the night away', 'Stayin Alive']);

// Matchers
provider.getSongs.calledWith(any()).mockReturnValue(['Saw her standing there']);
provider.getSongs.calledWith(anyString()).mockReturnValue(['Saw her standing there']);

You can also use mockFn() to create a jest.fn() with the calledWith extension:

 type MyFn = (x: number, y: number) => Promise<string>;
 const fn = mockFn<MyFn>();
 fn.calledWith(1, 2).mockReturnValue('str');

Clearing / Resetting Mocks

jest-mock-extended exposes a mockClear and mockReset for resetting or clearing mocks with the same functionality as jest.fn().

import { mock, mockClear, mockReset } from 'jest-mock-extended';

describe('test', () => {
   const mock: UserService = mock<UserService>();
   
   beforeEach(() => {
      mockReset(mock); // or mockClear(mock)
   });
   ...
})

Deep mocks

If your class has objects returns from methods that you would also like to mock, you can use mockDeep in replacement for mock.

import { mockDeep } from 'jest-mock-extended';

const mockObj = mockDeep<Test1>();
mockObj.deepProp.getNumber.calledWith(1).mockReturnValue(4);
expect(mockObj.deepProp.getNumber(1)).toBe(4);

Available Matchers

Matcher Description
any() Matches any arg of any type.
anyBoolean() Matches any boolean (true or false)
anyString() Matches any string including empty string
anyNumber() Matches any number that is not NaN
anyFunction() Matches any function
anyObject() Matches any object (typeof m === 'object') and is not null
anyArray() Matches any array
anyMap() Matches any Map
anySet() Matches any Set
isA(class) e.g isA(DiscoPartyProvider)
includes('value') Checks if value is in the argument array
containsKey('key') Checks if the key exists in the object
containsValue('value') Checks if the value exists in an object
has('value') checks if the value exists in a Set
notNull() value !== null
notUndefined() value !== undefined
notEmpty() value !== undefined && value !== null && value !== ''

Writing a Custom Matcher

Custom matchers can be written using a MatcherCreator

import { MatcherCreator, Matcher } from 'jest-mock-extended';

// expectedValue is optional
export const myMatcher: MatcherCreator<MyType> = (expectedValue) => new Matcher((actualValue) => {
    return (expectedValue === actualValue && actualValue.isSpecial);
});

By default, the expected value and actual value are the same type. In the case where you need to type the expected value differently than the actual value, you can use the optional 2 generic parameter:

import { MatcherCreator, Matcher } from 'jest-mock-extended';

// expectedValue is optional
export const myMatcher: MatcherCreator<string[], string> = (expectedValue) => new Matcher((actualValue) => {
    return (actualValue.includes(expectedValue));
});
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].