4

I am trying to mock a property of an object that acts as an object and as a function at the same time. Here's the code:

index.js

const nock = require('nock');

async function myFunc() {
  nock.back.setMode('param1');
  const { nockDone } = await nock.back('param1', 'param2');
  nock.enableNetConnect('param1');
  return nockDone;
}

module.exports = { myFunc }

My goal is to mock the nock object in a way I can assert that when myFunc is called, nock.back is called with param1 and param2.

To do so I have the following test:

index.test.js

const nock = require('nock');
const subjectUnderTest = require('./index');

const nockBackImplementation = jest.fn();
nockBackImplementation.setMode = jest.fn();

const nockBackMock = jest.spyOn(nock, 'back');
nockBackMock.mockImplementation(() => nockBackImplementation);

describe('test', () => {
  it('calls nock.back with the proper parameters', () => {
    subjectUnderTest.myFunc();

    expect(nockBackMock).toHaveBeenCalledWith('param1', 'param2');
  });
});

For some reason, the test fails saying that the mock function has not been called and also gives this error:

UnhandledPromiseRejectionWarning: TypeError: nock.back.setMode is not a function

I'm not sure how to properly mock nock.

diedu
  • 19,277
  • 4
  • 32
  • 49
Joan Vilà
  • 265
  • 5
  • 9

1 Answers1

0

You're assigning the setMode mock to the function used as implementation, which I think is different from the actual nock.back mock. You can set it correctly this way

const nockBackMock = jest
  .spyOn(nock, "back")
  .mockResolvedValue({ nockDone: "test" });
nockBackMock.setMode = jest.fn();
// you also need to mock the enableNetConnect to avoid errors
const enableNetConnectMock = jest
  .spyOn(nock, "enableNetConnect")
  .mockReturnValue({});

describe("test", () => {
  it("calls nock.back with the proper parameters", () => {
    subjectUnderTest.myFunc();

    expect(nockBackMock).toHaveBeenCalledWith("param1", "param2");
  });
});
diedu
  • 19,277
  • 4
  • 32
  • 49