Лучше не тестировать несколько модулей. Это означает, что для тестирования модуля requestsManager
вы должны имитировать модуль readiness
, а не косвенно модули state
и hooks
. Кроме того, jest.mock
следует использовать НЕ в области действия функции, его следует использовать в области модуля.
Например,
readiness.js
:
const state = require('./state');
const hooks = require('./hooks');
function setReady() {
state.ready = true;
hooks.notifyHook(state.ready);
}
function setNotReady() {
state.ready = false;
hooks.notifyHook(state.ready);
}
module.exports = {
setReady,
setNotReady,
};
hooks.js
:
function notifyHook() {}
module.exports = { notifyHook };
requestsManager.js
:
const readiness = require('./readiness');
function stopProcessNewRequests() {
readiness.setNotReady();
}
module.exports = { stopProcessNewRequests };
state.js
:
exports.ready = false;
exports.pendingRequests = {};
exports.changeStatusHooks = [];
exports.requestsInProcessNum = 0;
exports.authClient = null;
exports.webOperationsClient = null;
exports.webQueryClient = null;
Ниже тестовые файлы:
requestsManager.test.js
:
const { stopProcessNewRequests } = require('./requestsManager');
const readiness = require('./readiness');
describe('62057531', () => {
it('should pass', () => {
const setNotReadyMock = jest.spyOn(readiness, 'setNotReady').mockReturnValueOnce();
stopProcessNewRequests();
expect(setNotReadyMock).toBeCalledTimes(1);
});
});
readiness.test.js
:
const { setNotReady, setReady } = require('./readiness');
const hooks = require('./hooks');
const state = require('./state');
describe('62057531', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should set state to not ready', () => {
jest.spyOn(hooks, 'notifyHook').mockReturnValueOnce();
setNotReady();
expect(hooks.notifyHook).toBeCalledWith(false);
expect(state.ready).toBeFalsy();
});
it('should set state to ready', () => {
jest.spyOn(hooks, 'notifyHook').mockReturnValueOnce();
setReady();
expect(hooks.notifyHook).toBeCalledWith(true);
expect(state.ready).toBeTruthy();
});
});
Результаты модульного тестирования с отчетом о покрытии:
PASS stackoverflow/62057531/requestsManager.test.js (14.294s)
62057531
✓ should pass (6ms)
PASS stackoverflow/62057531/readiness.test.js
62057531
✓ should set state to not ready (5ms)
✓ should set state to ready (1ms)
--------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 75 | 100 |
hooks.js | 100 | 100 | 0 | 100 |
readiness.js | 100 | 100 | 100 | 100 |
requestsManager.js | 100 | 100 | 100 | 100 |
state.js | 100 | 100 | 100 | 100 |
--------------------|---------|----------|---------|---------|-------------------
Test Suites: 2 passed, 2 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 17.288s, estimated 21s