Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(ts-sinon): implementing ts-sinon package #603

Merged
merged 13 commits into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ node_modules/
lerna-debug.log
npm-debug.log
packages/*/lib
packages/testing/*/lib
.idea
coverage/
tsconfig.build.tsbuildinfo
Expand Down
8 changes: 4 additions & 4 deletions integration/rabbitmq/src/rpc/rpc-exception.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ export class RpcException extends Error {
isString((this.error as Record<string, any>).message)
) {
this.message = (this.error as Record<string, any>).message;
} else if (this.constructor) {
this.message = this.constructor.name
.match(/[A-Z][a-z]+|[0-9]+/g)
.join(' ');
} else if (this.constructor.name) {
const matchResult =
this.constructor.name.match(/[A-Z][a-z]+|[0-9]+/g) ?? [];
this.message = matchResult.join(' ');
}
}

Expand Down
5 changes: 4 additions & 1 deletion lerna.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"packages": ["packages/*"],
"packages": [
"packages/*",
"packages/testing/*"
],
"version": "independent",
"npmClient": "yarn",
"useWorkspaces": true,
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"license": "MIT",
"workspaces": [
"packages/*",
"packages/testing/*",
"integration/*"
],
"dependencies": {
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ For a few more examples on what can be done [the mock.spec](src/mocks.spec.ts) f

## Contribute

Contributions welcome! Read the [contribution guidelines](../../CONTRIBUTING.md) first.
Contributions welcome! Read the [contribution guidelines](../../../CONTRIBUTING.md) first.

## License

[MIT License](../../LICENSE)
[MIT License](../../../LICENSE)
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ describe('Mocks', () => {
const comparable = createMock<Service>();

expect([comparable]).toEqual([comparable]);
})
});
});
});

Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
{
"extends": "../../tsconfig.json",
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "./lib",
"rootDir": "./src"
},
"include": ["./src"]
"include": [
"./src"
]
}
94 changes: 94 additions & 0 deletions packages/testing/ts-sinon/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# @golevelup/ts-sinon

<p align="center">
<a href="https://www.npmjs.com/package/@golevelup/ts-sinon"><img src="https://img.shields.io/npm/v/@golevelup/ts-sinon.svg?style=flat" alt="version" /></a>
<a href="https://www.npmjs.com/package/@golevelup/ts-sinon"><img alt="downloads" src="https://img.shields.io/npm/dt/@golevelup/ts-sinon.svg?style=flat"></a>
<img alt="license" src="https://img.shields.io/npm/l/@golevelup/ts-sinon.svg">
</p>

## Motivation

With `@golevelup/ts-sinon`'s `createMock` utility function, you can easily generate deeply nested mock objects for unit
testing, especially useful for mocking complex types like those found in NestJS.

## Usage

This package is particularly handy when unit testing components in NestJS, but it's not limited to that. It can
essentially mock any TypeScript interface!

### Installation

```sh
npm i @golevelup/ts-sinon --save-dev
```

or

```sh
yarn add @golevelup/ts-sinon --dev
```

### Creating Mocks

1. Import the `createMock` function into your test class.
2. Create a variable and set it equal to the `createMock` function with its generic type input.
3. Use the mock, Luke.

Here's an example with NestJS' `ExecutionContext`:

```ts
import { createMock } from '@golevelup/ts-sinon';
import { ExecutionContext } from '@nestjs/common';

describe('Mocked Execution Context', () => {
it('should have a fully mocked Execution Context', () => {
const mockExecutionContext = createMock<ExecutionContext>();
expect(mockExecutionContext.switchToHttp()).toBeDefined();
});
});
```

`createMock` generates all sub-properties as `sinon.stub()`, so you can chain method calls:

```ts
it('should correctly resolve mocked providers', async () => {
const request = {
key: 'val',
};

mockExecutionContext.switchToHttp.returns(
createMock<HttpArgumentsHost>({
getRequest: () => request,
})
);

const mockResult = mockExecutionContext.switchToHttp().getRequest();
expect(mockResult).toBe(request);
});
```

You can also easily provide your own mocks:

```ts
const mockExecutionContext = createMock<ExecutionContext>({
switchToHttp: () => ({
getRequest: () => ({
headers: {
authorization: 'auth',
},
}),
getResponse: sinon.stub().returns({ data: 'res return data' }),
}),
});
```

> **Note**: When providing your own mocks, the number of times a parent mock function was called includes the times
> needed to set your mocks.

## Contribute

Contributions welcome! Read the [contribution guidelines](../../../CONTRIBUTING.md) first.

## License

[MIT License](../../../LICENSE)
5 changes: 5 additions & 0 deletions packages/testing/ts-sinon/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 61 additions & 0 deletions packages/testing/ts-sinon/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
{
"name": "@golevelup/ts-sinon",
"version": "0.0.0",
"description": "",
"author": "Omer Morad <[email protected]>",
"homepage": "https://github.com/golevelup/nestjs#readme",
"license": "MIT",
"keywords": [
"NestJS",
"testing",
"utilities",
"levelup",
"sinon"
],
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"directories": {
"lib": "lib",
"test": "__tests__"
},
"files": [
"lib"
],
"repository": {
"type": "git",
"url": "git+https://github.com/golevelup/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"
},
"peerDependencies": {
"sinon": "^14.x"
},
"devDependencies": {
"sinon": "^14.x",
"@types/sinon": "^10.0.15"
},
"publishConfig": {
"access": "public"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.ts$": "ts-jest"
},
"coverageDirectory": "../coverage",
"testEnvironment": "node"
},
"gitHead": "6f97aab8ce9d65dc074750a3ee467ec5ff3b9908"
}
1 change: 1 addition & 0 deletions packages/testing/ts-sinon/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './mocks';
Loading