Search code examples
typescriptjestjscreate-react-app

Jest throws TypeError: (0 , _module.myFunction) is not a function, testing exported functions (non default) with Jest


So I'm using Jest, Typescript and Create-react-app

I have this test:

import { defaultHeaders } from './http';

describe('http tests', () => {
  test('defaultHeaders()', () => {
    const headers = defaultHeaders(undefined);
    expect(headers).toEqual({ foo: 2 });
  });
});

The code is in same subdir in file http.ts and looks like this:

export function defaultHeaders(headers?: FetchHeaders): FetchHeaders {
  return { 'Content-Type': 'application/json' };
}

When I run my jest tests it throws:

TypeError: (0 , _http.defaultHeaders) is not a function

The weird part is that all other tests that are wrapped in a default function or const do work.

Is there any way to test non default exported functions with Jest?

update:

  • also tried converting defaultHeaders into an arrow function and that didn't help.
  • and tried changing import as: import * as http from './http' that still makes it throw same error

Solution

  • Update with Answer

    So the issue was that in src/setupTest.ts I included a mock of the module without the function I was trying to test therefore it was undefined.

    // mock our fetch wrapper to avoid doing http calls in tests
    jest.mock('utilities/http/http', () => ({
      // NO defaultHeaders() function mocked that was the problem 
      getRequest: function () {
        return {
          json: {},
          status: 200,
        };
      },
      postRequest: function () {
        return {
          json: {},
          status: 200,
        };
      },
      request: function () {
        return {
          json: {},
          status: 200,
        };
      },
    }));
    

    If I remove the mocked from setupTest.ts then I can unit test it.