{"_id":"@asanovr/ts-jest","name":"@asanovr/ts-jest","dist-tags":{"latest":"0.5.0"},"versions":{"0.5.0":{"name":"@asanovr/ts-jest","version":"0.5.0","description":"Reusable utilties to help level up NestJS Testing","author":{"name":"Jesse Carter","email":"jesse.r.carter@gmail.com"},"homepage":"https://github.com/golevelup/nestjs#readme","license":"MIT","keywords":["NestJS","testing","utilities","levelup"],"main":"lib/index.js","typings":"lib/index.d.ts","directories":{"lib":"lib","test":"__tests__"},"repository":{"type":"git","url":"git+https://github.com/asanovr/nestjs.git"},"scripts":{"build":"tsc --build tsconfig.build.json","build:watch":"tsc --build tsconfig.build.json --watch","test":"jest"},"bugs":{"url":"https://github.com/golevelup/nestjs/issues"},"publishConfig":{"access":"public"},"jest":{"moduleFileExtensions":["js","json","ts"],"rootDir":"src","testRegex":".spec.ts$","transform":{"^.+\\.ts$":"ts-jest"},"coverageDirectory":"../coverage","testEnvironment":"node"},"gitHead":"83abc8861cf5f8df94b8cd39964f41ce728aff6d","_id":"@asanovr/ts-jest@0.5.0","_nodeVersion":"16.15.1","_npmVersion":"lerna/3.22.1/node@v16.15.1+arm64 (darwin)","dist":{"integrity":"sha512-QKbRrprQ/Oge9Fsytns/8bOisrOHMS9qxXuYRxf36MiwELSmQXNRFdVjT6uqNBYllCdyMO8iz9+XAZXsfeSXZg==","shasum":"5993fd90659f1a31cfad728a7bc9a7bbe91c59d4","tarball":"https://registry.npmjs.org/@asanovr/ts-jest/-/ts-jest-0.5.0.tgz","fileCount":12,"unpackedSize":20858,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIHK3TK8wSFWrZCU+9OcIBgzY8yfbeSzR4503tuT9YkabAiEArlHOrduIuH6oNQsIMvZuL2CiC1Qzfm78FtXVmkSGhfs="}]},"_npmUser":{"name":"asanovr","email":"bioforge91@gmail.com"},"maintainers":[{"name":"asanovr","email":"bioforge91@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/ts-jest_0.5.0_1693545916351_0.7825739043423725"},"_hasShrinkwrap":false}},"time":{"created":"2023-09-01T05:25:16.250Z","0.5.0":"2023-09-01T05:25:16.492Z","modified":"2023-09-01T05:25:16.786Z"},"maintainers":[{"name":"asanovr","email":"bioforge91@gmail.com"}],"description":"Reusable utilties to help level up NestJS Testing","homepage":"https://github.com/golevelup/nestjs#readme","keywords":["NestJS","testing","utilities","levelup"],"repository":{"type":"git","url":"git+https://github.com/asanovr/nestjs.git"},"author":{"name":"Jesse Carter","email":"jesse.r.carter@gmail.com"},"bugs":{"url":"https://github.com/golevelup/nestjs/issues"},"license":"MIT","readme":"# @golevelup/ts-jest\n\n<p align=\"center\">\n<a href=\"https://www.npmjs.com/package/@golevelup/ts-jest\"><img src=\"https://img.shields.io/npm/v/@golevelup/ts-jest.svg?style=flat\" alt=\"version\" /></a>\n<a href=\"https://www.npmjs.com/package/@golevelup/ts-jest\"><img alt=\"downloads\" src=\"https://img.shields.io/npm/dt/@golevelup/ts-jest.svg?style=flat\"></a>\n<img alt=\"license\" src=\"https://img.shields.io/npm/l/@golevelup/ts-jest.svg\">\n</p>\n\n## Description\n\nUtilities for making testing [NestJS](https://docs.nestjs.com) applications easier. Currently supports Jest.\n\n## Motivation\n\nYou ever just come across a type that you want to mock, but mocking the entire object seems daunting, and who knows how many sub properties the object has and if those sub properties have sub properties. The list goes on with possible problems. Enter `@golevelup/ts-jest`'s `createMock` utility function. This function will create a mock object for you with all sub properties mocked as `jest.fn()` unless otherwise provided, to allow for easy mocking later on, but more on that later.\n\n### Side Note\n\nThis package and utility function was derived out of a want to help those unit testing things like [Guards](https://docs.nestjs.com/guards), [Interceptors](https://docs.nestjs.com/interceptors), and [Filters](https://docs.nestjs.com/exception-filters), in NestJS; however, given the dynamic nature of the package, the `createMock` utility function can handle so much more than just what's inside of NestJS. Essentially, if it has an interface, `@golevelup/ts-jest` can mock it!\n\n## Usage\n\nFor examples we'll show how well it works with NestJS' [ExecutionContext](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/execution-context.interface.ts) which extends NestJS' [ArgumentHost](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/features/arguments-host.interface.ts#L60).\n\n### Installation\n\nPretty standard installation, nothing too crazy\n\n```sh\nnpm i @golevelup/ts-jest --save-dev\n```\n\nor\n\n```sh\nyarn add @golevelup/ts-jest --dev\n```\n\n### Creating Mocks\n\nHere is where the fun begins. As a heads up, this function **does** require you to be using Typescript, as it takes advantage of some advanced Typescript features under the hood, like `Proxies`.\n\n1. Import the `createMock` function into your test class\n2. Create a variable and set it equal to the `createMock` function **plus** its generic type input\n3. Use the mock, Luke.\n\nExample:\n\n```ts\nimport { createMock } from '@golevelup/ts-jest';\nimport { ExecutionContext } from '@nestjs/common';\n\ndescribe('Mocked Execution Context', () => {\n  it('should have a fully mocked Execution Context', () => {\n    const mockExecutionContext = createMock<ExecutionContext>();\n    expect(mockExecutionContext.switchToHttp()).toBeDefined();\n  });\n});\n```\n\nAnd just like that, the simplest mock can quickly and easily be made! \"Big deal\" you may say? It's easy to create a mock with a single property like that? Well, just watch this:\n\n```ts\nimport { createMock } from '@golevelup/ts-jest';\nimport { ExecutionContext } from '@nestjs/common';\n\ndescribe('Mocked Execution Context', () => {\n  it('should have a fully mocked Execution Context', () => {\n    const mockExecutionContext = createMock<ExecutionContext>();\n    expect(mockExecutionContext.switchToHttp().getRequest()).toBeDefined();\n    expect(mockExecutionContext.switchToRPC().getContext()).toBeDefined();\n    expect(mockExecutionContext.switchToWs().getClient()).toBeDefined();\n  });\n});\n```\n\nHow's that for ya? No, still not impressed? All right, time to bring out the big guns.\n\n```ts\nimport { createMock } from '@golevelup/ts-jest';\nimport { ExecutionContext } from '@nestjs/common';\n\ndescribe('Mocked Execution Context', () => {\n  it('should have a fully mocked Execution Context', () => {\n    const mockExecutionContext = createMock<ExecutionContext>({\n      switchToHttp: () => ({\n        getRequest: () => ({\n          headers: {\n            authorization: 'auth',\n          },\n        }),\n      }),\n    });\n    mockExecutionContext\n      .switchToHttp()\n      .getResponse.mockReturnValue({ data: 'res return data' });\n    expect(mockExecutionContext.switchToHttp().getRequest()).toEqual({\n      headers: {\n        authorization: 'auth',\n      },\n    });\n    expect(mockExecutionContext.switchToHttp().getResponse()).toEqual({\n      data: 'res return data',\n    });\n    expect(mockExecutionContext.switchToHttp).toBeCalledTimes(3);\n    expect(mockExecutionContext.switchToRPC().getContext()).toBeDefined();\n    expect(mockExecutionContext.switchToWs().getClient()).toBeDefined();\n  });\n});\n```\n\n> **Note**: Be aware that when providing your own mocks, if you asserting how many times you called a parent mock function, the number will be equal to the number of times the function was called in your `expects` _plus_ the number of times the function had to be called to set your mocks. In the above case, we had to call `switchToHttp()` once to set the mock for `getResponse()` and twice for the `expect` calls, so it was called in a total of three times.\n\nThe above case shows how well the `createMock` utility can take in user provided values as well as returning **type safe** mocks that can easily be chained and modified as needed.\n\nFor a few more examples on what can be done [the mock.spec](src/mocks.spec.ts) file has some really cool examples that show pretty well just what is doable with this utility.\n\n## Contribute\n\nContributions welcome! Read the [contribution guidelines](../../../CONTRIBUTING.md) first.\n\n## License\n\n[MIT License](../../../LICENSE)\n","readmeFilename":"README.md"}