Вы можете использовать jest.spyOn (object, methodName) и mockImplementation
, чтобы перезаписать исходную функцию поддельной.
Например
file.js
:
const log = { trace: console.log };
const REAL_CLIENT_REQUEST = 'REAL_CLIENT_REQUEST';
function handleRequest(grpcRequestObj, callback) {
const refId = '1';
if (grpcRequestObj.type === REAL_CLIENT_REQUEST) {
log.trace('Запрос от реального клиента', refId);
module.exports.realClientRequestWay(grpcRequestObj, callback);
return;
}
}
function realClientRequestWay(grpcRequestObj, callback) {
//some logic
}
module.exports = {
handleRequest,
realClientRequestWay,
};
file.test.js
:
const file = require('./file');
describe('62079376', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should request', () => {
jest.spyOn(file, 'realClientRequestWay').mockImplementationOnce();
const mCallback = jest.fn();
file.handleRequest({ type: 'REAL_CLIENT_REQUEST' }, mCallback);
expect(file.realClientRequestWay).toBeCalledWith({ type: 'REAL_CLIENT_REQUEST' }, mCallback);
});
it('should do nothing if type not match', () => {
jest.spyOn(file, 'realClientRequestWay').mockImplementationOnce();
const mCallback = jest.fn();
file.handleRequest({ type: '' }, mCallback);
expect(file.realClientRequestWay).not.toBeCalled();
});
});
Результаты модульного тестирования со 100% покрытием:
PASS stackoverflow/62079376/file.test.js (10.044s)
62079376
✓ should request (16ms)
✓ should do nothing if type not match (1ms)
console.log
Запрос от реального клиента 1
at Object.handleRequest (stackoverflow/62079376/file.js:7:9)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
file.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 11.393s, estimated 12s