How to check if mocked inner function has been called in jest?

Viewed 2877

here is my file under test:

file.js:

function handleRequest(grpcRequestObj, callback){

    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
}

test file:


    test("should call real clients way", ()=>{
        jest.mock("../lib/grpc/state");

        const state = require("../lib/grpc/state");
        state.ready = true;
        const constants = require("../lib/grpc/constants");
        const handleRequestModule = require("../lib/grpc/handleRequest");
        const { handleRequest } = jest.requireActual("../lib/grpc/handleRequest");

        handleRequestModule.realClientRequestWay = jest.fn();

        const grpcRequest = {
            type: constants.REAL_CLIENT_REQUEST,
            refId: "123"
        };
        const mockCb = jest.fn();
        handleRequest(grpcRequest, mockCb);
        expect(handleRequestModule.realClientRequestWay).toHaveBeenCalledTimes(1);
    });

I am mocking realClientRequestWay fucntion to be a jest mock function just to check if it runs, but it is not calling, what am I doing wrong?

1 Answers

You can use jest.spyOn(object, methodName) and mockImplementation to overwrite the original function with a mocked one.

E.g.

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();
  });
});

unit test results with 100% coverage:

 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
Related