Skip to content
Advertisement

In Jest, how do I cause a function called within the function to return a specific value

This is the function I am testing (stripped down for simplicity’s sake): populate.js->

const { createSessionID } = require('./populate-template-utilities');

const createFile = async () => {
  const responseHeader = {};
  responseHeader.SessionID = createSessionID();
  return responseHeader;
};

module.exports = {
  createFile,
};

The function this function calls: populate-template-utilities ->

const createSessionID = () => {
  const digits = (Math.floor(Math.random() * 9000000000) + 1000000000).toString();
  return `PAX${digits}`;
};

module.exports = {
  createSessionID,
};

And my unit test (again stripped down):

const { createSessionID } = require('../app/lib/populate-template-utilities');

describe('create XML for output files', () => {

  const mockID = jest
    .spyOn(createSessionID)
    .mockImplementation(() => 'PAX123456');

  it('should create a PAX File', async () => {
    const result = await createFile();
    expect(result).toEqual(getFile);
  });
});

I want createSessionID to return ‘PAX123456’ and think mockID should do it, but it’s erroring with:

Cannot spy the undefined property because it is not a function; undefined given instead

Advertisement

Answer

The spyOn method needs at least two parameters: object and methodName.

Try sth like this:

import * as populateTemplateUtils from "../sessionStuff";
import { createFile } from "../createFile";

describe('create XML for output files', () => {
  it('should create a PAX File', async () => {
    jest
      .spyOn(populateTemplateUtils, 'createSessionID')
      .mockReturnValue('PAX123456');

    const result = await createFile();
    expect(result).toEqual({"SessionID": "PAX123456"});
  });
});

It all started to work when I changed the:

module.exports = {
  createSessionID,
};

to:

export const createSessionID = () => {
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement