Testing
Test tools, services, and pipeline classes with Jest
NitroStack servers are ordinary TypeScript classes, so you test them with ordinary tools. Unit tests call a tool's method directly with a mock context; the testing module builds your providers with mocks in place of real dependencies; integration tests run tools through the full pipeline.
Setup
Tests run with Jest and ts-jest, so TypeScript tests need no separate build step.
Install Dependencies
Add Jest and its TypeScript support as development dependencies:
npm install --save-dev jest @types/jest ts-jestJest Configuration
Tell Jest to compile TypeScript and where to find tests:
// jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
}
};Package.json Script
Add scripts so npm test runs the suite:
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
}
}Testing Module
TestingModule builds a small version of your app for a test: the providers you list, with mocks wherever you override them.
Import Testing Utilities
Everything comes from @nitrostack/core/testing:
import {
TestingModule,
CompiledTestingModule,
createMockContext,
createMockFn,
spyOn,
MockLogger
} from '@nitrostack/core/testing';TestingModule
Create a testing module to test your services and components in isolation with dependency injection:
import { TestingModule, CompiledTestingModule } from '@nitrostack/core/testing';
import { ProductService } from '../products/products.service.js';
import { DatabaseService } from '../database/database.service.js';
describe('ProductService', () => {
let compiled: CompiledTestingModule;
let productService: ProductService;
let mockDatabaseService: { query: jest.Mock; queryOne: jest.Mock };
beforeEach(() => {
mockDatabaseService = {
query: jest.fn(),
queryOne: jest.fn(),
};
compiled = TestingModule.create()
.addProvider(ProductService)
.addMock(DatabaseService, mockDatabaseService)
.compile();
productService = compiled.get(ProductService);
});
afterEach(() => {
compiled.cleanup();
});
it('should be defined', () => {
expect(productService).toBeDefined();
});
});Testing topics
Unit Tests
Tools, services, middleware, and interceptors.
Integration Tests
Run tools through the full pipeline.
Mocks and Coverage
Mock helpers and coverage reports.
