Skip to content

Commit cfdf43c

Browse files
committed
feat(spectator): move spectator code into repo
1 parent 3bcaa2f commit cfdf43c

16 files changed

+497
-1
lines changed

nx.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@
3131
"playground-e2e": {
3232
"tags": [],
3333
"implicitDependencies": ["playground"]
34+
},
35+
"spectator": {
36+
"tags": []
3437
}
3538
},
3639
"workspaceLayout": {

packages/spectator/.eslintrc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{ "extends": "../../.eslintrc", "rules": {}, "ignorePatterns": ["!**/*"] }

packages/spectator/README.md

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
<h1 align="center">Welcome to nest-spectator 👋</h1>
2+
<p>
3+
<a href="https://www.npmjs.com/package/nest-spectator" target="_blank">
4+
<img alt="Version" src="https://img.shields.io/npm/v/nest-spectator.svg">
5+
</a>
6+
<a href="#" target="_blank">
7+
<img alt="License: MIT" src="https://img.shields.io/badge/License-MIT-yellow.svg" />
8+
</a>
9+
</p>
10+
11+
> Auto-mocking for Nestjs providers
12+
13+
### 🏠 [Homepage](https://www.npmjs.com/package/nest-spectator)
14+
15+
## Author
16+
17+
👤 **Jay Bell <[email protected]>**
18+
19+
## Usage
20+
21+
See `packages/nest-spectator/__tests__` for reference:
22+
23+
Let's assume you we have the following 2 different Nestjs services:
24+
25+
```
26+
@Injectable()
27+
class PrimaryService {
28+
constructor(secondaryService: SecondaryService) {
29+
}
30+
31+
testFunction(): string {
32+
return 'test';
33+
}
34+
}
35+
```
36+
37+
and
38+
39+
```
40+
@Injectable()
41+
class SecondaryService {
42+
}
43+
```
44+
45+
and this controller:
46+
47+
```
48+
@Controller()
49+
class PrimaryController {
50+
constructor(primaryService: PrimaryService) {
51+
}
52+
}
53+
```
54+
55+
Currently we have something like:
56+
57+
```
58+
import { Test } from '@nestjs/testing';
59+
import { PrimaryController } from './primary.controller';
60+
import { PrimaryService } from './primary.service';
61+
import { SecondaryService } from './secondary.service';
62+
63+
describe('PrimaryController', () => {
64+
let primaryController: PrimaryController;
65+
let primaryService: PrimaryService;
66+
67+
beforeEach(async () => {
68+
const module = await Test.createTestingModule({
69+
controllers: [PrimaryController],
70+
providers: [PrimaryService, SecondaryService],
71+
}).compile();
72+
73+
primaryService = module.get<PrimaryService>(PrimaryService);
74+
primaryController = module.get<PrimaryController>(PrimaryController);
75+
});
76+
});
77+
```
78+
79+
Which is fine for small projects but as your code base grows you could have many injections in your classes constructor that you are testing.
80+
Assuming you plan on creating mocks for the services injected into `PrimaryController` classes or you want to spy on the classes methods of `PrimaryService` your code can start to grow more and more for each time you have a new spec file.
81+
82+
If you do not mock our your services and instead just want to spy on them, your spec files will grow very large because each service you provider in the `Test.createTestingModule` will need to have all of it's services injected as well.
83+
84+
You can see the effect of this in the sample above, `SecondaryService` is injected because `PrimaryService` injects it which in turn is injected into `PrimaryController`
85+
86+
If you are wanting to create mocks for each of these services injected in your class being tested then it would look something like this:
87+
88+
```
89+
import { Test } from '@nestjs/testing';
90+
import { PrimaryController } from './primary.controller';
91+
import { PrimaryService } from './primary.service';
92+
import { SecondaryService } from './secondary.service';
93+
94+
const mockPrimaryService = {
95+
testFunction: () => {}
96+
}
97+
98+
class MockPrimaryService {
99+
testFunction(): void {
100+
}
101+
}
102+
103+
describe('PrimaryController', () => {
104+
let primaryController: PrimaryController;
105+
let primaryService: PrimaryService;
106+
107+
beforeEach(async () => {
108+
const module = await Test.createTestingModule({
109+
controllers: [PrimaryController],
110+
providers: [
111+
{provide: PrimaryService, useValue: mockPrimaryService}
112+
// OR
113+
{provide: PrimaryService, useClass: MockPrimaryService}
114+
],
115+
}).compile();
116+
117+
primaryService = module.get<PrimaryService>(PrimaryService);
118+
primaryController = module.get<PrimaryController>(PrimaryController);
119+
});
120+
});
121+
```
122+
123+
Now you will have to maintain these mock objects for each of your services and ensure you provide over your implementation services in each of your spec files.
124+
125+
This is where `nest-spectator` comes in, inspired by [@ngneat/spectator](https://github.com/ngneat/spectator) for Angular, `nest-spectator` creates a layer on top of the `@nestjs/testing`
126+
`Test.creatingTestingModule` to provide the functionality to auto mock your services so that your module instantiation in tests turns into:
127+
128+
```
129+
beforeEach(async () => {
130+
module = await createTestingModuleFactory(
131+
{
132+
imports: [],
133+
controllers: [PrimaryController],
134+
providers: [PrimaryService],
135+
mocks: [PrimaryService]
136+
},
137+
).compile();
138+
});
139+
```
140+
141+
The `createTestingModuleFactory` accepts all the same values as the `Test.createTestingModule` function except that there is an option property `mocks?: Array<Type<any>>`
142+
that will accept the providers you want to auto mock. This function will return the same value (`TestingModuleBuilder`) as `Test.createTestingModule` will which means we just call
143+
`.compile()` on it after to get our testing module.
144+
145+
If we need access to our services provided to this testing module we get them the same way as we would before since we just have a `TestingModule`.
146+
147+
```
148+
const primaryService = module.get<PrimaryService>(PrimaryService);
149+
```
150+
151+
If `PrimaryService` was included in the `mocks` array during test module instantiation than it will be an object that mirrors the structure of your class as if it was provided normally except
152+
that the methods, getters and setters will all be `jest` Spys themselves.
153+
154+
When providing `PrimaryService` in the mocks array and using `module.get<T>(T)` to get the instance of the provider it will return `SpyObject<PrimaryService>` instead of just `PrimaryService`.
155+
156+
This package is still in alpha so there way be unintended side effects or gaps in the logic. If there is anything you would like to see include please feel free to open an issue.
157+
158+
## 🤝 Contributing
159+
160+
Contributions, issues and feature requests are welcome!<br />Feel free to check [issues page](https://github.com/yharaskrik/nest-testing/issues). You can also take a look at the [contributing guide](https://www.npmjs.com/package/nest-spectator/blob/master/CONTRIBUTING.md).
161+
162+
## Show your support
163+
164+
Give a ⭐️ if this project helped you!
165+
166+
---
167+
168+
_This README was generated with ❤️ by [readme-md-generator](https://github.com/kefranabg/readme-md-generator)_

packages/spectator/jest.config.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
module.exports = {
2+
name: 'spectator',
3+
preset: '../../jest.config.js',
4+
globals: {
5+
'ts-jest': {
6+
tsConfig: '<rootDir>/tsconfig.spec.json',
7+
},
8+
},
9+
transform: {
10+
'^.+\\.[tj]sx?$': 'ts-jest',
11+
},
12+
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
13+
coverageDirectory: '../../coverage/packages/spectator',
14+
};

packages/spectator/package.json

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
{
2+
"name": "@nestjs-addons/spectator",
3+
"version": "0.0.11",
4+
"description": "Auto-mocking for Nestjs providers",
5+
"author": "Jay Bell <[email protected]>",
6+
"homepage": "https://www.npmjs.com/package/nest-spectator",
7+
"license": "MIT",
8+
"main": "lib/index.js",
9+
"typings": "lib/index.d.ts",
10+
"directories": {
11+
"lib": "lib",
12+
"test": "__tests__"
13+
},
14+
"files": [
15+
"lib"
16+
],
17+
"repository": {
18+
"type": "git",
19+
"url": "https://github.com/nestjs-addons/platform"
20+
},
21+
"bugs": {
22+
"url": "https://github.com/nestjs-addons/platform"
23+
},
24+
"keywords": [
25+
"nestjs",
26+
"nest",
27+
"typescript",
28+
"testing",
29+
"jest"
30+
]
31+
}

packages/spectator/src/index.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export * from './lib/testing-module';
2+
export * from './lib/mock';
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { OptionalsRequired } from '../types';
2+
3+
/**
4+
* @internal
5+
*/
6+
export function merge<T>(
7+
defaults: OptionalsRequired<T>,
8+
overrides?: T,
9+
): Required<T> {
10+
return { ...defaults, ...overrides } as Required<T>;
11+
}

packages/spectator/src/lib/mock.ts

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
/** Credit to: Valentin Buryakov
2+
* @ngneat/spectator - https://github.com/ngneat/spectator
3+
*/
4+
import { Provider, Type } from '@nestjs/common';
5+
import { FactoryProvider } from '@nestjs/common/interfaces';
6+
7+
type Writable<T> = { -readonly [P in keyof T]: T[P] };
8+
9+
/**
10+
* @publicApi
11+
*/
12+
export type BaseSpyObject<T> = T &
13+
{ [P in keyof T]: T[P] extends Function ? T[P] & CompatibleSpy : T[P] } & {
14+
/**
15+
* Casts to type without readonly properties
16+
*/
17+
castToWritable(): Writable<T>;
18+
};
19+
20+
/**
21+
* @publicApi
22+
*/
23+
export interface CompatibleSpy extends jasmine.Spy {
24+
/**
25+
* By chaining the spy with and.returnValue, all calls to the function will return a specific
26+
* value.
27+
*/
28+
andReturn(val: any): void;
29+
30+
/**
31+
* By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied
32+
* function.
33+
*/
34+
andCallFake(fn: Function): this;
35+
36+
/**
37+
* removes all recorded calls
38+
*/
39+
reset(): void;
40+
}
41+
42+
/**
43+
* @publicApi
44+
*/
45+
export type SpyObject<T> = BaseSpyObject<T> &
46+
{
47+
[P in keyof T]: T[P] &
48+
(T[P] extends (...args: any[]) => infer R ? jest.Mock<R> : T[P]);
49+
};
50+
51+
/**
52+
* @internal
53+
*/
54+
export function installProtoMethods<T>(
55+
mock: any,
56+
proto: any,
57+
createSpyFn: Function,
58+
): void {
59+
if (proto === null || proto === Object.prototype) {
60+
return;
61+
}
62+
63+
for (const key of Object.getOwnPropertyNames(proto)) {
64+
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
65+
66+
if (!descriptor) {
67+
continue;
68+
}
69+
70+
if (
71+
typeof descriptor.value === 'function' &&
72+
key !== 'constructor' &&
73+
typeof mock[key] === 'undefined'
74+
) {
75+
mock[key] = createSpyFn(key);
76+
} else if (descriptor.get && !mock.hasOwnProperty(key)) {
77+
Object.defineProperty(mock, key, {
78+
set: (value) => (mock[`_${key}`] = value),
79+
get: () => mock[`_${key}`],
80+
});
81+
}
82+
}
83+
84+
installProtoMethods(mock, Object.getPrototypeOf(proto), createSpyFn);
85+
86+
mock.castToWritable = () => mock;
87+
}
88+
89+
/**
90+
* @publicApi
91+
*/
92+
export function createSpyObject<T>(
93+
type: Provider<T> & { prototype: T },
94+
template?: Partial<Record<keyof T, any>>,
95+
): SpyObject<T> {
96+
const mock: any = { ...template } || {};
97+
98+
installProtoMethods(mock, type.prototype, () => {
99+
const jestFn = jest.fn();
100+
const newSpy: CompatibleSpy = jestFn as any;
101+
102+
newSpy.andCallFake = (fn: Function) => {
103+
jestFn.mockImplementation(fn as (...args: any[]) => any);
104+
105+
return newSpy;
106+
};
107+
108+
newSpy.andReturn = (val: any) => {
109+
jestFn.mockReturnValue(val);
110+
};
111+
112+
newSpy.reset = () => {
113+
jestFn.mockReset();
114+
};
115+
116+
return newSpy;
117+
});
118+
119+
return mock;
120+
}
121+
122+
/**
123+
* @publicApi
124+
*/
125+
export function mockProvider<T>(
126+
type: Type<T>,
127+
properties?: Partial<Record<keyof T, any>>,
128+
): FactoryProvider {
129+
return {
130+
provide: type,
131+
useFactory: () => createSpyObject(type, properties),
132+
};
133+
}

0 commit comments

Comments
 (0)