{"id":13623508,"url":"https://github.com/marchaos/jest-mock-extended","last_synced_at":"2025-05-14T14:07:28.083Z","repository":{"id":36229502,"uuid":"221873890","full_name":"marchaos/jest-mock-extended","owner":"marchaos","description":"Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended","archived":false,"fork":false,"pushed_at":"2024-09-06T22:39:20.000Z","size":567,"stargazers_count":874,"open_issues_count":35,"forks_count":61,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-19T10:08:39.651Z","etag":null,"topics":["calledwith","jest","mock","mocking-framework","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/marchaos.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-11-15T08:00:42.000Z","updated_at":"2025-04-10T11:21:34.000Z","dependencies_parsed_at":"2024-01-12T10:27:01.904Z","dependency_job_id":"e649f18c-a7a9-45a1-b414-b991cb951348","html_url":"https://github.com/marchaos/jest-mock-extended","commit_stats":{"total_commits":143,"total_committers":27,"mean_commits":5.296296296296297,"dds":"0.49650349650349646","last_synced_commit":"18609501e1b78acfb9d3d522b61f9c03d67022a7"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marchaos%2Fjest-mock-extended","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marchaos%2Fjest-mock-extended/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marchaos%2Fjest-mock-extended/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/marchaos%2Fjest-mock-extended/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/marchaos","download_url":"https://codeload.github.com/marchaos/jest-mock-extended/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254159194,"owners_count":22024558,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["calledwith","jest","mock","mocking-framework","typescript"],"created_at":"2024-08-01T21:01:32.571Z","updated_at":"2025-05-14T14:07:28.061Z","avatar_url":"https://github.com/marchaos.png","language":"TypeScript","funding_links":[],"categories":["Packages","TypeScript"],"sub_categories":["Mocks"],"readme":"# jest-mock-extended\n\u003e Type safe mocking extensions for Jest 🃏\n\n[![Build Status](https://travis-ci.com/marchaos/jest-mock-extended.svg?branch=master)](https://travis-ci.com/marchaos/jest-mock-extended)\n[![Coverage Status](https://coveralls.io/repos/github/marchaos/jest-mock-extended/badge.svg?branch=master)](https://coveralls.io/github/marchaos/jest-mock-extended?branch=master)\n[![npm version](https://badge.fury.io/js/jest-mock-extended.svg)](https://badge.fury.io/js/jest-mock-extended)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![npm downloads](https://badgen.net/npm/dw/jest-mock-extended)](https://badge.fury.io/js/jest-mock-extended)\n\n## Features\n- Provides complete Typescript type safety for interfaces, argument types and return types\n- Ability to mock any interface or object\n- calledWith() extension to provide argument specific expectations, which works for objects and functions.\n- Extensive Matcher API compatible with Jasmine matchers\n- Supports mocking deep objects / class instances.\n- Familiar Jest like API\n\n## Installation\n```bash\nnpm install jest-mock-extended --save-dev\n```\nor\n```bash\nyarn add jest-mock-extended --dev\n```\n\n## Example\n\n```ts\nimport { mock } from 'jest-mock-extended';\n\ninterface PartyProvider {\n   getPartyType: () =\u003e string;\n   getSongs: (type: string) =\u003e string[]\n   start: (type: string) =\u003e void;\n}\n\ndescribe('Party Tests', () =\u003e {\n   test('Mock out an interface', () =\u003e {\n       const mock = mock\u003cPartyProvider\u003e();\n       mock.start('disco party');\n       \n       expect(mock.start).toHaveBeenCalledWith('disco party');\n   });\n   \n   \n   test('mock out a return type', () =\u003e {\n       const mock = mock\u003cPartyProvider\u003e();\n       mock.getPartyType.mockReturnValue('west coast party');\n       \n       expect(mock.getPartyType()).toBe('west coast party');\n   });\n\n    test('throwing an error if we forget to specify the return value')\n        const mock = mock\u003cPartyProvider\u003e(\n            {},\n            {\n                fallbackMockImplementation: () =\u003e {\n                    throw new Error('not mocked');\n                },\n            }\n        );\n\n        expect(() =\u003e mock.getPartyType()).toThrowError('not mocked');\n    });\n```\n\n## Assigning Mocks with a Type\n\nIf you wish to assign a mock to a variable that requires a type in your test, then you should use the MockProxy\u003c\u003e type\ngiven that this will provide the apis for calledWith() and other built-in jest types for providing test functionality.\n\n```ts\nimport { MockProxy, mock } from 'jest-mock-extended';\n\ndescribe('test', () =\u003e {\n    let myMock: MockProxy\u003cMyInterface\u003e;\n\n    beforeEach(() =\u003e {\n        myMock = mock\u003cMyInterface\u003e();\n    })\n\n    test(() =\u003e {\n         myMock.calledWith(1).mockReturnValue(2);\n         ...\n    })\n});\n\n```\n\n## calledWith() Extension\n\n```jest-mock-extended``` allows for invocation matching expectations. Types of arguments, even when using matchers are type checked.\n\n```ts\nconst provider = mock\u003cPartyProvider\u003e();\nprovider.getSongs.calledWith('disco party').mockReturnValue(['Dance the night away', 'Stayin Alive']);\nexpect(provider.getSongs('disco party')).toEqual(['Dance the night away', 'Stayin Alive']);\n\n// Matchers\nprovider.getSongs.calledWith(any()).mockReturnValue(['Saw her standing there']);\nprovider.getSongs.calledWith(anyString()).mockReturnValue(['Saw her standing there']);\n\n```\nYou can also use ```mockFn()``` to create a ```jest.fn()``` with the calledWith extension:\n\n```ts\n type MyFn = (x: number, y: number) =\u003e Promise\u003cstring\u003e;\n const fn = mockFn\u003cMyFn\u003e();\n fn.calledWith(1, 2).mockReturnValue('str');\n```\n\n## Clearing / Resetting Mocks\n\n```jest-mock-extended``` exposes a mockClear and mockReset for resetting or clearing mocks with the same \nfunctionality as ```jest.fn()```.\n\n```ts\nimport { mock, mockClear, mockReset } from 'jest-mock-extended';\n\ndescribe('test', () =\u003e {\n   const mock: UserService = mock\u003cUserService\u003e();\n   \n   beforeEach(() =\u003e {\n      mockReset(mock); // or mockClear(mock)\n   });\n   ...\n})\n```\n\n## Deep mocks\n\nIf your class has objects returns from methods that you would also like to mock, you can use ```mockDeep``` in \nreplacement for mock.\n\n```ts\nimport { mockDeep } from 'jest-mock-extended';\n\nconst mockObj: DeepMockProxy\u003cTest1\u003e = mockDeep\u003cTest1\u003e();\nmockObj.deepProp.getNumber.calledWith(1).mockReturnValue(4);\nexpect(mockObj.deepProp.getNumber(1)).toBe(4);\n```\nif you also need support for properties on functions, you can pass in an option to enable this\n\n```ts\nimport { mockDeep } from 'jest-mock-extended';\n\nconst mockObj: DeepMockProxy\u003cTest1\u003e = mockDeep\u003cTest1\u003e({ funcPropSupport: true });\nmockObj.deepProp.calledWith(1).mockReturnValue(3)\nmockObj.deepProp.getNumber.calledWith(1).mockReturnValue(4);\n\nexpect(mockObj.deepProp(1)).toBe(3);\nexpect(mockObj.deepProp.getNumber(1)).toBe(4);\n```\n\nCan can provide a fallback mock implementation used if you do not define a return value using `calledWith`.\n\n```ts\nimport { mockDeep } from 'jest-mock-extended';\nconst mockObj = mockDeep\u003cTest1\u003e({\n    fallbackMockImplementation: () =\u003e {\n        throw new Error('please add expected return value using calledWith');\n    },\n});\nexpect(() =\u003e mockObj.getNumber()).toThrowError('not mocked');\n```\n\n\n## Available Matchers\n\n\n| Matcher               | Description                                                           |\n|-----------------------|-----------------------------------------------------------------------|\n|any()                  | Matches any arg of any type.                                          |\n|anyBoolean()           | Matches any boolean (true or false)                                   |\n|anyString()            | Matches any string including empty string                             |\n|anyNumber()            | Matches any number that is not NaN                                    |\n|anyFunction()          | Matches any function                                                  |\n|anyObject()            | Matches any object (typeof m === 'object') and is not null            |\n|anyArray()             | Matches any array                                                     |\n|anyMap()               | Matches any Map                                                       |\n|anySet()               | Matches any Set                                                       |\n|isA(class)             | e.g isA(DiscoPartyProvider)                                           |\n|includes('value')      | Checks if value is in the argument array                              |\n|containsKey('key')     |  Checks if the key exists in the object                               |\n|containsValue('value') | Checks if the value exists in an object                               |\n|has('value')           | checks if the value exists in a Set                                   |\n|notNull()              | value !== null                                                        |\n|notUndefined()         | value !== undefined                                                   |\n|notEmpty()             | value !== undefined \u0026\u0026 value !== null \u0026\u0026 value !== ''                 |\n|captor()               | Used to capture an arg - alternative to mock.calls[0][0]              |\n\n## Writing a Custom Matcher\n\nCustom matchers can be written using a ```MatcherCreator```\n\n```ts\nimport { MatcherCreator, Matcher } from 'jest-mock-extended';\n\n// expectedValue is optional\nexport const myMatcher: MatcherCreator\u003cMyType\u003e = (expectedValue) =\u003e new Matcher((actualValue) =\u003e {\n    return (expectedValue === actualValue \u0026\u0026 actualValue.isSpecial);\n});\n```\n\nBy default, the expected value and actual value are the same type. In the case where you need to type the expected value \ndifferently than the actual value, you can use the optional 2 generic parameter:\n\n```ts\nimport { MatcherCreator, Matcher } from 'jest-mock-extended';\n\n// expectedValue is optional\nexport const myMatcher: MatcherCreator\u003cstring[], string\u003e = (expectedValue) =\u003e new Matcher((actualValue) =\u003e {\n    return (actualValue.includes(expectedValue));\n});\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarchaos%2Fjest-mock-extended","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmarchaos%2Fjest-mock-extended","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmarchaos%2Fjest-mock-extended/lists"}