1

I've got function provided by lib (project dependency from NPM). This function has a signature like

function dependency(
  someParam: string,
  callback: (data: string) => void
): void { ... }

This function has been called by my function (that I need to test) in the way like below:

async function tested(): Promise<string> {
  return new Promise<string>((resolve): void => dependency('qwerty', resolve));
}

I need to test my tested function with Jest but I'd like to test it in the unit-test style, so I need to mock the result from dependency. This example is pretty simple, but in reality there are some additional logic that I need to give different data from dependency.

Spying on this function informs me that it's being called, but I need to mock implementation and completely prevent executing of the lib's implementation.

halfer
  • 19,824
  • 17
  • 99
  • 186
WeekendMan
  • 561
  • 1
  • 10
  • 25
  • there are several ways to achieve that: [`jest.mock` with factory method](https://jestjs.io/docs/en/es6-class-mocks#calling-jestmock-docs-en-jest-object-jestmockmodulename-factory-options-with-the-module-factory-parameter) or `jest.mock` + `import` + `mockImplementation` to mock module, and a lot of different `.mock*` methods to mock results or implementation. Better provide your code you have by now for test itself. – skyboyer Aug 26 '19 at 12:46
  • Possible duplicate of [How can I mock an ES6 module import using Jest?](https://stackoverflow.com/questions/40465047/how-can-i-mock-an-es6-module-import-using-jest) – Jared Smith Aug 26 '19 at 16:05
  • @skyboyer, `implementation will also be executed when the mock is called` (for `mockImplementation`). I don't need that. @JaredSmith, thank you for providing this link, I've learnt a lot about how to be sure that dependency was called. Now can you show me where exactly is the answer on my question there and why is it a duplication? :) – WeekendMan Aug 27 '19 at 05:32
  • mock implementation ≠ original function – skyboyer Aug 27 '19 at 07:00
  • Yes, but the text that I copied was taken from JSDocs, so, I presume, original implementation will be called along with fake one? Or...? – WeekendMan Aug 27 '19 at 07:56

1 Answers1

0

Here is a simple working example to get you started:

lib.ts

export function dependency(
  someParam: string,
  callback: (data: string) => void
): void {
  throw new Error('should never get here');
}

code.ts

import { dependency } from './lib';

export async function tested(): Promise<string> {
  return new Promise<string>((resolve): void => dependency('qwerty', resolve));
}

code.test.ts

import * as lib from './lib';
import { tested } from './code';

test('tested', async () => {
  const mock = jest.spyOn(lib, 'dependency');
  mock.mockImplementation((someParam, callback) => {
    callback('mocked result');
  });
  const result = await tested();
  expect(result).toBe('mocked result');  // Success!
})
Brian Adams
  • 43,011
  • 9
  • 113
  • 111