'How can I use jest to spyOn an internal function?

2 questions in 1 here.

Why do I get an error message for my jest.spyOn saying that createMappingsDirectory is not a function?

Secondly, I think where I’ve put createDirectories in the spyOn, this should be the name of the file which is ‘populate-templates.js’. However, if I put this in without quotes, I get an error: ‘ReferenceError: populate is not defined’.

And with quotes: ‘Cannot spyOn on a primitive value; string given’

What should I do?

const {
  createDirectories,
  createStubsDirectory,
  createMappingsDirectory,
} = require('../app/populate-templates');

it('should create the stubs/mappings directory', async () => {
  const mappingsSpy = jest.spyOn(createDirectories, 'createMappingsDirectory', 'createStubsDirectory');
  await createDirectories();
  expect(mappingsSpy).toHaveBeenCalledTimes(1);
});

populate-templates.js

const createDirectories = async () => {
  let msg = await createStubsDirectory();
  logger.info(msg);
  msg = await createMappingsDirectory();
  logger.info(msg);
}; 

module.exports = {
  createStubsDirectory,
  createMappingsDirectory,
  createDirectories,
};



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source