Skip to content

"TypeError: Cannot read property 'then' of undefined" when mocking async function with Jest #11027

@gfox1984

Description

@gfox1984

Describe the bug

I have the following interface in TypeScript:

interface Something {
  getValueAsync: () => Promise<number>
}

I'm trying to create a mock instance with Jest:

const mock : Something = {
  getValueAsync: jest.fn().mockResolvedValue(123),
};

When running the tests, the tested component that receives the mock fails with:

TypeError: Cannot read property 'then' of undefined

   7 |
   8 |   useEffect(() => {
>  9 |     if (something) something.getValueAsync().then(setValue);
     |                    ^
  10 |   }, [something]);

Note that the instance of something is retrieved via the context, if ever that's relevant

Did you try recovering your dependencies?

I created a fresh app to reproduce the issue.

Which terms did you search for in User Guide?

I searched for Jest TypeError: Cannot read property 'then' of undefined

Environment

> npx create-react-app --info
npx: installed 67 in 5.771s

Environment Info:

  current version of create-react-app: 4.0.3
  running from C:\Users\guill\AppData\Roaming\npm-cache\_npx\6932\node_modules\create-react-app

  System:
    OS: Windows 10 10.0.19042
    CPU: (8) x64 Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz
  Binaries:
    Node: 14.15.4 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.10 - C:\Program Files\nodejs\yarn.CMD
    npm: 6.14.10 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Chrome: 91.0.4472.77
    Edge: Spartan (44.19041.964.0), Chromium (90.0.818.66)
    Internet Explorer: 11.0.19041.1
  npmPackages:
    react: ^17.0.2 => 17.0.2
    react-dom: ^17.0.2 => 17.0.2
    react-scripts: 4.0.3 => 4.0.3
  npmGlobalPackages:
    create-react-app: Not Found

Steps to reproduce

Follow the steps in bug description, or clone the repo at https://github.com/gfox1984/jest-async, then run the tests

Expected behavior

All tests to pass (the component should render the mocked value '123')

Actual behavior

The error reported in bug description occurs.

Reproducible demo

https://github.com/gfox1984/jest-async, then run the tests

Beware, I could only reproduce the issue when cloning the repo locally (the same repo on codesandbox works as expected: https://codesandbox.io/s/pensive-pine-m481d?file=/src/SomethingComponent.test.tsx)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions