typescript
53 lines · 7 steps
Unit testing a NestJS service with mocked providers
Wiring fake repositories and gateways into a NestJS test module to verify a service in isolation.
Explained by
highlit
1import { Test, TestingModule } from '@nestjs/testing';
2import { getRepositoryToken } from '@nestjs/typeorm';
3import { Repository } from 'typeorm';
4
5import { UsersService } from './users.service';
6import { PaymentGateway } from '../payments/payment.gateway';
7import { User } from './entities/user.entity';
8
9describe('UsersService', () => {
10 let service: UsersService;
11 let paymentGateway: jest.Mocked<PaymentGateway>;
12
13 const userRepository = {
14 findOne: jest.fn(),
15 save: jest.fn(),
16 create: jest.fn((dto) => dto),
17 };
18
19 beforeEach(async () => {
20 const module: TestingModule = await Test.createTestingModule({
21 providers: [
22 UsersService,
23 {
24 provide: getRepositoryToken(User),
25 useValue: userRepository,
26 },
27 {
28 provide: PaymentGateway,
29 useValue: {
30 createCustomer: jest.fn().mockResolvedValue({ id: 'cus_123' }),
31 charge: jest.fn(),
32 },
33 },
34 ],
35 }).compile();
36
37 service = module.get(UsersService);
38 paymentGateway = module.get(PaymentGateway);
39 });
40
41 it('provisions a payment customer when registering', async () => {
42 userRepository.findOne.mockResolvedValue(null);
43 userRepository.save.mockImplementation(async (u: User) => ({ id: 1, ...u }));
44
45 const user = await service.register({
46 email: 'ada@example.com',
47 password: 'hunter2',
48 });
49
50 expect(paymentGateway.createCustomer).toHaveBeenCalledWith('ada@example.com');
51 expect(user.stripeCustomerId).toBe('cus_123');
52 });
53});
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Overriding providers with useValue lets you swap real dependencies for controllable test doubles.
- 2getRepositoryToken resolves the injection token TypeORM uses so you can mock a repository cleanly.
- 3Asserting on mocked collaborators verifies a service's side effects without hitting a real database or API.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/unit-testing-a-nestjs-service-with-mocked-providers-explained-typescript-38bd/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.