TypeScriptTesting
Mocks and Coverage
Mock helpers from @nitrostack/core/testing, and coverage reports
@nitrostack/core/testing provides helpers for building mock contexts and services, and Jest reports which code your tests cover.
Mock Utilities
These helpers cover the setup most tests need.
createMockContext
Builds an ExecutionContext with a no-op logger and any fields you pass.
const ctx = createMockContext({
auth: {
subject: 'user-123',
token: 'fake-token',
role: 'admin'
},
metadata: {
custom: 'value'
}
});createMockFn
Creates a typed mock function whose return values you control.
const mockFn = createMockFn<(input: any) => Promise<any>>();
mockFn.mockResolvedValue({ success: true });
mockFn.mockRejectedValue(new Error('Failed'));spyOn
Wraps an existing method so you can check how it was called, or change what it returns.
const spy = spyOn(service, 'methodName');
spy.mockReturnValue('mocked value');
spy.mockImplementation((arg) => `modified ${arg}`);
expect(spy).toHaveBeenCalledWith('arg');
expect(spy).toHaveBeenCalledTimes(1);Test Coverage
Coverage shows which lines your tests never run.
Run Coverage
Generate a coverage report:
npm run test:coverageCoverage Goals
Aim for:
- Statements: > 80%
- Branches: > 70%
- Functions: > 80%
- Lines: > 80%
Jest Configuration
Choose which files count toward coverage, and fail the run if coverage drops below a threshold:
// jest.config.js
module.exports = {
collectCoverageFrom: [
'src/**/*.ts',
'!src/**/*.spec.ts',
'!src/**/*.test.ts',
'!src/**/index.ts'
],
coverageThresholds: {
global: {
branches: 70,
functions: 80,
lines: 80,
statements: 80
}
}
};