In my case, I had to mock a Node.js module. I'm using React and Redux in ES6, with Jest and Enzyme for unit tests.

In the file I'm using, and writing a test for, I'm importing the node modules as default:

import nodeModulePackage from 'nodeModulePackage';

So I needed to mock it as a default since I kept getting the error (0, _blah.default) is not a function..

My solution was to do:

jest.mock('nodeModulePackage', () => jest.fn(() => {}));

In my case, I just needed to override the function and make it return an empty object.

If you need to call a function on that node module, you'll do the following:

jest.mock('nodeModulePackage', () => ({ doSomething: jest.fn(() => 'foo') }));
Answer from jenkizenki on Stack Overflow
Discussions

Why do I keep getting type error, "x" is not a function when using jest with create-react-app?

You need to do 'export default' in the sum function if you want to import the function without unpacking. Otherwise, you need to unpack when importing like 'import {sum} from...'

More on reddit.com
🌐 r/webdev
1
0
June 12, 2018
Writing tests: type error not a function
Hi, It is my first time writing tests, using jest. The error says that sortEvents is not a function even though it is: import React from "react"; import ReactDOM from "react-dom"; import App from "./components/App"; i… More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
5
0
May 6, 2019
React Jest - TypeError: (0 , _[....]) is not a function
I'm trying to create unit tests with Jest for a React application and unfortunelly getting errors after importing any component into my tests. The error appears on every function that I have. The More on stackoverflow.com
🌐 stackoverflow.com
Unit testing with jest in React Native project ("Not a function" error)
I am working on a React Native project (v0.46). I've been able to write component snapshot tests successfully, but I'm having trouble wrapping my head around unit testing JavaScript ES6 functions. ... More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 1
1

Here is the unit test solution using jestjs and react-dom/test-utils:

index.tsx:

import React, { FC, useState, useEffect } from 'react';
import { GetTotal } from './getTotal';

interface Props {
  activeTab: string;
}

function handleCount(dates: object, setCount: Function, activeTab?: string) {
  const totalCount = new GetTotal(dates, activeTab);
  setCount(totalCount.totalAttendances());
}

export function handleYearTab(setCount: Function, activeTab: string) {
  if (activeTab === 'Year') {
    handleCount(new Date(), setCount, activeTab);
  }
}

const Content: FC<Props> = ({ activeTab }) => {
  const [count, setCount] = useState<number>(0);

  useEffect(() => {
    handleYearTab(setCount, activeTab);
  });

  return <div>{count}</div>;
};

export default Content;

getTotal.ts:

export class GetTotal {
  constructor(dates, activeTab) {}
  public totalAttendances(): number {
    return 1;
  }
}

index.test.tsx:

import Content from './';
import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { act } from 'react-dom/test-utils';
import { GetTotal } from './getTotal';

describe('60638277', () => {
  let container;
  beforeEach(() => {
    container = document.createElement('div');
    document.body.appendChild(container);
  });

  afterEach(() => {
    unmountComponentAtNode(container);
    container.remove();
    container = null;
  });
  it('should handle year tab', async () => {
    const totalAttendancesSpy = jest.spyOn(GetTotal.prototype, 'totalAttendances').mockReturnValue(100);
    const mProps = { activeTab: 'Year' };
    await act(async () => {
      render(<Content {...mProps}></Content>, container);
    });
    expect(container.querySelector('div').textContent).toBe('100');
    expect(totalAttendancesSpy).toBeCalled();
    totalAttendancesSpy.mockRestore();
  });

  it('should render initial count', async () => {
    const mProps = { activeTab: '' };
    await act(async () => {
      render(<Content {...mProps}></Content>, container);
    });
    expect(container.querySelector('div').textContent).toBe('0');
  });
});

unit test results with coverage report:

 PASS  stackoverflow/60638277/index.test.tsx (9.331s)
  60638277
    ✓ should handle year tab (32ms)
    ✓ should render initial count (11ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-------------|---------|----------|---------|---------|-------------------
All files    |   95.24 |      100 |   85.71 |   94.12 |                   
 getTotal.ts |      80 |      100 |   66.67 |      75 | 4                 
 index.tsx   |     100 |      100 |     100 |     100 |                   
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        10.691s

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60638277

🌐
Reddit
reddit.com › r/webdev › why do i keep getting type error, "x" is not a function when using jest with create-react-app?
r/webdev on Reddit: Why do I keep getting type error, "x" is not a function when using jest with create-react-app?
June 12, 2018 -
// sum.js
export const sum = (a,b) => a+b

// sum.test.js
import sum from './sum';

it('sums numbers', () => {
  expect(sum(1, 2)).toEqual(3);
  expect(sum(2, 2)).toEqual(4);
});

I'm new to writing unit tests. I'm trying to write tests for my reducers and actions. However I can't seem to test a simple function that adds two numbers. I keep getting,

TypeError: (0 , _sum2.default) is not a function

What should I do??? Thanks.

🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Writing tests: type error not a function - JavaScript
May 6, 2019 - Hi, It is my first time writing tests, using jest. The error says that sortEvents is not a function even though it is: import React from "react"; import ReactDOM from "react-dom"; import App from "./components/App"; i…
🌐
Medium
dana-scheider.medium.com › troubleshooting-jest-with-react-environment-setup-is-not-a-function-9132569b5215
Troubleshooting Jest with React: environment.setup is not a function | by Dana Scheider (he/they) | Medium
June 2, 2018 - This is a short post about how I fixed a Jest error with my React app. This error affected two things: Jest test runs failed with the error TypeError: environment.setup is not a function.
Find elsewhere
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Jest Testing, ...is not a function - JavaScript
May 12, 2022 - I’ve already successfully exported ... way, but this one doesn’t want to work. The problem function in question is the generateCoordinates method inside the gameboardFactory function....
🌐
Stack Overflow
stackoverflow.com › questions › 49821962 › jest-mock-is-not-a-function-in-react
jest.mock is not a function in react?
I've updated your answer. You might want to tweak your title and clarify a bit in your question that you want to test what is inside the function, not that it is called. 2018-04-13T17:42:29.02Z+00:00 ... You didn't include jest.mock('axios') after the imports in your .spec file.
🌐
GitHub
github.com › vercel › next.js › issues › 63868
Jest/Vitest unit testing: TypeError: (0 , _reactdom.useFormStatus) is not a function · Issue #63868 · vercel/next.js
March 29, 2024 - Current Receive error: TypeError: useFormStatus is not a function · Expected No error received and rest of test able to be evaluated. Operating System: Platform: win32 Arch: x64 Version: Windows 10 Enterprise Binaries: Node: 20.11.0 npm: N/A Yarn: N/A pnpm: N/A Relevant Packages: next: 14.1.1 eslint-config-next: N/A react: 18.2.0 react-dom: 18.2.0 typescript: N/A Next.js Config: output: N/A · Jest (next/jest), TypeScript (plugin, built-in types) next dev (local) If I modify the button component and remove the useFormStatus hook, the test will pass.
Author   vercel
🌐
Stack Overflow
stackoverflow.com › questions › 73719411 › react-jest-testing-typeerror-refetch-is-not-a-function
reactjs - React - Jest testing - TypeError: refetch is not a function - Stack Overflow
Sign up to request clarification or add additional context in comments. ... Thanks for your reply Gaurav, same error unfortunately though. 2022-09-14T16:53:44.76Z+00:00 ... const useStudentsMock = jest.mock('hooks/Student/useStudents'); useStudentsMock..mockImplementation(() => ({ isLoading: false, data: [], // you mock data refetch: jest.fn() }));
🌐
DhiWise
dhiwise.com › post › fix-typeerror-expect-tobeinthedocument-is-not-a-function
Fix 'Typeerror Expect Tobeinthedocument Is Not A Function ...
April 12, 2024 - By importing @testing-library/jest-dom, you make additional matchers like .toBeInTheDocument() available in all test files. Now that we have our testing environment configured, let's address the typeerror expect tobeinthedocument is not a function.
🌐
Stack Overflow
stackoverflow.com › questions › 57764495 › type-error-is-not-a-function-in-a-jest-test
reactjs - "Type Error : is not a function" in a Jest test - Stack Overflow
September 3, 2019 - A component tested by Jest and Enzyme has some function. Then this function uses an imported library. It makes some error. Test code it('Emoji should be rendered without error', () => { const
🌐
GitHub
github.com › redux-observable › redux-observable › issues › 286
TypeError is not a function in jest test · Issue #286 · redux-observable/redux-observable
July 29, 2017 - I took this pattern from https://stackoverflow.com/a/43599309 by @jayphelps This pattern works in usage but breaks in Jest tests. I get the error · ● Test suite failed to run TypeError: _Observable.Observable.merge is not a function
Author   redux-observable
🌐
GitHub
github.com › jestjs › jest › issues › 4613
jest.fn() is not a function · Issue #4613 · jestjs/jest
October 6, 2017 - I'm trying to simulate 'onSubmit' by using jest but it throws an error on 'jest.fn()' saying jest.fn() is not a function but in every example, I see everyone imports jest and uses it. Is this a bug or do I miss something? "jest": "^21.2....
Author   jestjs