Skip to content

Commit d6aeb14

Browse files
Merge pull request #2102 from jmcdo29/feat/auto-mock
feat: add new documentation around auto-mocking capabilities
2 parents ac822f7 + 1603177 commit d6aeb14

File tree

1 file changed

+44
-8
lines changed

1 file changed

+44
-8
lines changed

content/fundamentals/unit-testing.md

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,41 @@ Instead of using the production version of any provider, you can override it wit
160160

161161
<app-banner-courses></app-banner-courses>
162162

163+
#### Auto mocking
164+
165+
Nest also allows you to define a mock factory to apply to all of your missing dependencies. This is useful for cases where you have a large number of dependencies in a class and mocking all of them will take a long time and a lot of setup. To make use of this feature, the `createTestingModule()` will need to be chained up with the `useMocker()` method, passing a factory for your dependency mocks. This factory can take in an optional token, which is an instance token, any token which is valid for a Nest provider, and returns a mock implementation. The below is an example of creating a generic mocker using [`jest-mock`](https://www.npmjs.com/package/jest-mock) and a specific mock for `CatsService` using `jest.fn()`.
166+
167+
```typescript
168+
const moduleMocker = new ModuleMocker(global);
169+
170+
describe('CatsController', () => {
171+
let controller: CatsController;
172+
173+
beforeEach(async () => {
174+
const moduleRef = await Test.createTestingModule({
175+
controllers: [CatsController],
176+
})
177+
.useMocker((token) => {
178+
if (token === CatsService) {
179+
return { findAll: jest.fn().mockResolveValue(results) };
180+
}
181+
if (typeof token === 'function') {
182+
const mockMetadata = moduleMocker.getMetadata(token) as MockFunctionMetadata<any, any>;
183+
const Mock = moduleMocker.generateFromMetadata(mockMetadata);
184+
return new Mock();
185+
}
186+
})
187+
.compile();
188+
189+
controller = moduleRef.get(CatsController);
190+
});
191+
})
192+
```
193+
194+
> info **Hint** A general mock factory, like `createMock` from [`@golevelup/ts-jest`](https://github.com/golevelup/nestjs/tree/master/packages/testing) can also be passed directly.
195+
196+
You can also retrieve these mocks out of the testing container as you normally would custom providers, `moduleRef.get(CatsService)`.
197+
163198
#### End-to-end testing
164199

165200
Unlike unit testing, which focuses on individual modules and classes, end-to-end (e2e) testing covers the interaction of classes and modules at a more aggregate level -- closer to the kind of interaction that end-users will have with the production system. As an application grows, it becomes hard to manually test the end-to-end behavior of each API endpoint. Automated end-to-end tests help us ensure that the overall behavior of the system is correct and meets project requirements. To perform e2e tests we use a similar configuration to the one we just covered in **unit testing**. In addition, Nest makes it easy to use the [Supertest](https://github.com/visionmedia/supertest) library to simulate HTTP requests.
@@ -243,26 +278,27 @@ describe('Cats', () => {
243278
>
244279
> ```ts
245280
> let app: NestFastifyApplication;
246-
>
281+
>
247282
> beforeAll(async () => {
248283
> app = moduleRef.createNestApplication<NestFastifyApplication>(
249284
> new FastifyAdapter(),
250285
> );
251286
>
252287
> await app.init();
253288
> await app.getHttpAdapter().getInstance().ready();
254-
> })
255-
>
289+
> });
290+
>
256291
> it(`/GET cats`, () => {
257292
> return app
258293
> .inject({
259294
> method: 'GET',
260-
> url: '/cats'
261-
> }).then(result => {
262-
> expect(result.statusCode).toEqual(200)
263-
> expect(result.payload).toEqual(/* expectedPayload */)
295+
> url: '/cats',
296+
> })
297+
> .then((result) => {
298+
> expect(result.statusCode).toEqual(200);
299+
> expect(result.payload).toEqual(/* expectedPayload */);
264300
> });
265-
> })
301+
> });
266302
> ```
267303
268304
In this example, we build on some of the concepts described earlier. In addition to the `compile()` method we used earlier, we now use the `createNestApplication()` method to instantiate a full Nest runtime environment. We save a reference to the running app in our `app` variable so we can use it to simulate HTTP requests.

0 commit comments

Comments
 (0)