{"id":13660539,"url":"https://github.com/ilancohen/jest-class-mocker","last_synced_at":"2025-04-24T19:31:09.499Z","repository":{"id":57280256,"uuid":"174135852","full_name":"ilancohen/jest-class-mocker","owner":"ilancohen","description":"Jest mocks for TypesScript Classes","archived":false,"fork":false,"pushed_at":"2019-03-13T14:15:34.000Z","size":64,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-13T14:51:15.958Z","etag":null,"topics":["jest","jest-mocking","mock","typescript","unit-testing"],"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/ilancohen.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}},"created_at":"2019-03-06T11:53:20.000Z","updated_at":"2020-04-12T22:39:00.000Z","dependencies_parsed_at":"2022-09-19T15:11:16.899Z","dependency_job_id":null,"html_url":"https://github.com/ilancohen/jest-class-mocker","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilancohen%2Fjest-class-mocker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilancohen%2Fjest-class-mocker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilancohen%2Fjest-class-mocker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ilancohen%2Fjest-class-mocker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ilancohen","download_url":"https://codeload.github.com/ilancohen/jest-class-mocker/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250693543,"owners_count":21472274,"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":["jest","jest-mocking","mock","typescript","unit-testing"],"created_at":"2024-08-02T05:01:22.767Z","updated_at":"2025-04-24T19:31:09.207Z","avatar_url":"https://github.com/ilancohen.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# jest-class-mocker\n\nJest mocks for unit tests for [TypeScript classes](https://www.typescriptlang.org/docs/handbook/classes.html). This will allow you to easily mock TypeScript classes,\n(which are similar to ES6 classes). It also has automatic instantiation and mocking of a class' dependencies.\n\nThe mocks generated are type-safe with deep typing, allowing for TypeScript to catch any syntax or type errors, and modern code-completing editors to help with writing testss\n\n---\n\n## Examples\n\n```typescript\nconst classMockInstance = generateMockInstance(ClassA);\nclassMockInstance.method1('abc');\nexpect(classMockInstance.method1).toHaveBeenCalled();\nexpect(classMockInstance.method1.mock.calls).toEqual([['abc']]);\n```\n\n```typescript\nconst {classInstance, dependencies, resetAllMocks} = instantiateWithMocks(ClassA, {ClassB, ClassC});\nclassInstance.methodThatReliesOnDependencies('abc');\nexpect(dependencies.ClassB.method1).toHaveBeenCalled();\nexpect(dependencies.ClassC.method2).toHaveBeenCalled();\n```\n\n---\n\n## Getting Started\n\nAll you need to do is install the package (see below) and ```import```\n\n### Prerequisites\n\n#### Jest\n\nThis project uses [Jest](https://jestjs.io/) for its [mock functions](https://jestjs.io/docs/en/mock-function-api).\nTechnically, you can use it in a project using a different testing framework, but it is not intended for such.\n\n### Installing\n\nTo install, all you need to do is:\n\n```\nnpm install jest-class-mocker\n```\n\nAnd then\n\n```\nimport {generateMockInstance, instantiateWithMocks} from \"jest-class-mocker\";\n```\n\nThen use these functions as per the API below.\n\n## API\n\n#### generateMockInstance\\\u003cClassTypeToMock\\\u003e(ClassConstructor) ⇒ \u003ccode\u003emockedClassInstance\u003c/code\u003e\nThis function takes a class constructor and returns a type-safe mocked class instance with all of the instance methods of that class.\n\nUse the generic type syntax `\u003cClassTypeToMock\u003e` (see the example below) to ensure a fully type-safe return value.\n\n##### Parameters:\n\n| Param  | Type                | Description  |\n| ------ | ------------------- | ------------ |\n| ClassConstructor  | `constructor function` | the function that is used with `new` |\n\n##### Return Value:\n`MockOf\u003cClassTypeToMock\u003e`\n\nThis is a type defined by the package. It includes all of the methods and properties of a normal class instance of `ClassToMock`, plus the `mockReset` function which resets all of the mocked functions.\n\n##### Example:\n```typescript\nclass ClassA {\n    property1 = 1;\n\n    method1(arg1: string): string {\n        return arg1 + 'abc';\n    }\n}\n\nconst classMockInstance = generateMockInstance\u003cClassA\u003e(ClassA);\nclassMockInstance.method1.mockReturnValue('mockRetVal');\nconst retVal = classMockInstance.method1('abc');\nexpect(classMockInstance.method1).toHaveBeenCalled();\nexpect(classMockInstance.method1.mock.calls).toEqual([['abc']]);\nexpect(retVal).toEqual('mockRetVal');\n```\n\n**Note**: This only creates mock instance _methods_. While the instance _properties_ of the class are part of the TypeScript type definition, their values will be `undefined` during runtime unless set explicitly:\n\n```typescript\nconst classAMock = generateMockInstance\u003cClassA\u003e(ClassA);\nexpect(classAMock.function1).toBeDefined();\nexpect(classAMock.property1).toBeUndefined();\n```\n    \n  \n        \n  ***\n\n\n#### instantiateWithMocks(ClassToInstantiate, dependencyClasses) ⇒ \u003ccode\u003e{classInstance, dependencies, resetAllMocks}\u003c/code\u003e\nThis function takes a class constructor and its dependency class constructor and returns a class instance,\nplus mock instances (using `generateMockInstance`) with all of the instance methods of that class.\nIt also returns a convenience method for resetting all functions in all dependencies.\n\n##### Parameters:\n\n| Param  | Type                | Description  |\n| ------ | ------------------- | ------------ |\n| ClassToInstantiate  | \u003ccode\u003econstructor function\u003c/code\u003e | the function that is used with \u003ccode\u003enew\u003c/code\u003e to create the class you want to instantiate. |\n| dependencies  | \u003ccode\u003eobject literal of constructor functions OR values to use for dependencies\u003c/code\u003e | Class constructor in an object literal, using the class name as the key. See the example below. |\n\n\n##### Return Values (in the returned object literal):\n| Param  | Type                | Description  |\n| ------ | ------------------- | ------------ |\n| classInstance  | instance of \u003ccode\u003eClassToInstantiate\u003c/code\u003e | A new instance of \u003ccode\u003eClassToInstantiate\u003c/code\u003e, using mocked instances for its dependencies. |\n| dependencies  | \u003ccode\u003eobject literal containing mocks of all passed dependencies\u003c/code\u003e | The mocked instances used to create \u003ccode\u003eclassInstance\u003c/code\u003e\n| resetAllMocks  | \u003ccode\u003e() =\u003e void\u003c/code\u003e | A convenience function, equivalent to calling \u003ccode\u003emockReset()\u003c/code\u003e on each of the dependencies.\n\n\n**Important Note:**\n\nThis function relies on Object keys being **ordered**, and therefore, the dependencies **must** be passed in the order\nthat the class expects to receive them as parameters.\n\n\n##### Example:\n```typescript\nclass ClassA {\n    function1(): string {\n        return 'abc';\n    }\n}\n\nclass ClassB {\n    function2(): string {\n        return 'def';\n    }\n}\n\nclass ClassC {\n    constructor(\n        private name: 'abc',\n        private classA: ClassA,\n        private classB: ClassB\n    ) {}\n\n    functionThatReliesOnDependencies() {\n        return this.classA.function1() + this.classB.function2();\n    }\n}\n\nconst {classInstance, dependencies, resetAllMocks} = instantiateWithMocks(ClassC, {name: 'abc', ClassA, ClassB});\nexpect(dependencies.ClassA).toBeDefined();\nexpect(dependencies.ClassB).toBeDefined();\n\ndependencies.ClassA.function1.mockReturnValue('first');\ndependencies.ClassB.function2.mockReturnValue('second');\n\nconst result = classInstance.functionThatReliesOnDependencies();\n\nexpect(dependencies.ClassA.function1).toHaveBeenCalled();\nexpect(dependencies.ClassB.function2).toHaveBeenCalled();\nexpect(result).toEqual('firstsecond');\n```\n\n## Authors\n\n* **Ilan Cohen** - *Initial work* - [Ilan Cohen](https://github.com/ilancohen)\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details\n\n## Acknowledgments\n\n* Thanks to [ffMathy](https://github.com/ffMathy) from whose [Substitute](https://github.com/ffMathy/FluffySpoon.JavaScript.Testing.Faking) project I borrowed (with permission) some advanced TypeScript types.\n* Special thanks to [Ben Grynhaus](https://github.com/bengry) for helping me muddle through some of the more complicated aspects of advanced TypeScript types.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Filancohen%2Fjest-class-mocker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Filancohen%2Fjest-class-mocker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Filancohen%2Fjest-class-mocker/lists"}