@jonrsharpe mentioned
testing at the integration layer.
It is known as black-box testing. This type of test only looks at the external behavior of the system, without considering the internal workings of the software. It focuses on the behavior of the software.
Perhaps you are interested in White-box testing. White Box Testing is a technique used to test software while taking its internal functioning into account.
Main Contrasts
- Black Box Testing only looks at the external behavior of the system, while White Box Testing considers its internal functioning.
- When performing Black Box Testing, knowledge of implementation is not necessary, unlike White Box Testing.
- Black Box Testing generally takes less time than White Box Testing.
Below is an example of white-box unit testing:
errorHandler.ts
:
import express from 'express';
export function errorHandler() {
return (error: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
if ((error as any).type === 'entity.too.large') {
error = new Error(error.message);
}
if (!res.headersSent) {
res.status(500).json({ success: false, errorCode: 'sys_entity_too_large' });
}
next();
};
}
errorHandler.test.ts
:
import { errorHandler } from './errorHandler';
import express from 'express';
describe('errorHandler', () => {
test('should send error', () => {
const mw = errorHandler();
class CustomError extends Error {
constructor(public type: string, message?: string) {
super(message);
this.stack = new Error().stack;
this.name = this.constructor.name;
}
}
const mError = new CustomError('entity.too.large', 'test error message');
const mRes = ({
headersSent: false,
status: jest.fn().mockReturnThis(),
json: jest.fn(),
} as unknown) as express.Response;
const mNext = jest.fn() as express.NextFunction;
const mReq = {} as express.Request;
mw(mError, mReq, mRes, mNext);
expect(mRes.status).toBeCalledWith(500);
expect(mRes.json).toBeCalledWith({ success: false, errorCode: 'sys_entity_too_large' });
expect(mNext).toBeCalledTimes(1);
});
});
Test results:
PASS stackoverflow/72882415/errorHandler.test.ts (10.401 s)
errorHandler
✓ should send error (5 ms)
-----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------------|---------|----------|---------|---------|-------------------
All files | 100 | 50 | 100 | 100 |
errorHandler.ts | 100 | 50 | 100 | 100 | 5-9
-----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.021 s