Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

_userEvent.default.setup is not a function #839

Closed
Tommoore96 opened this issue Jan 20, 2022 · 38 comments · Fixed by #949
Closed

_userEvent.default.setup is not a function #839

Tommoore96 opened this issue Jan 20, 2022 · 38 comments · Fixed by #949
Labels

Comments

@Tommoore96
Copy link

  • @testing-library/user-event version: ^14.0.0-beta
  • DOM Environment: 8.11.1
  • Node version: 14.17.4

Relevant code or config

const user = userEvent.setup()

What you did:
Tests worked perfectly before updating, I just wanted the latest version for the pointer method.

Followed the latest documentation and tried multiple versions 14 and above.

Imported like so:

import userEvent from '@testing-library/user-event';

and initialised like so:

const user = userEvent.setup()

What happened:
Tests failed and receive following error:
TypeError: _userEvent.default.setup is not a function

@ph-fritsche
Copy link
Member

_userEvent.default.setup suggests that the import statement is transpiled before being executed.

Could you please provide a reproduction?

@ph-fritsche ph-fritsche added this to the userEvent v14 milestone Feb 4, 2022
@bijay-ps
Copy link

bijay-ps commented Feb 9, 2022

I am also facing the same issue.
Here is what I did:

import userEvent from "@testing-library/user-event";

test("Should be able to type an email", () => { const user = userEvent.setup(); render(<App/>) const emailInputElement = screen.getByRole("textbox", { name: /email/i}) user.type(emailInputElement, "test@test.com"); expect(emailInputElement.value).toBe("test@test.com"); })

Output:
TypeError: _userEvent.default.setup is not a function

This is my jest and RTL versions:
"@testing-library/jest-dom": "^5.16.2",
"@testing-library/react": "^12.1.2",
"@testing-library/user-event": "^13.5.0",

@ph-fritsche
Copy link
Member

@bijay-ps userEvent.setup() was introduced in v14.

@nickmccurdy
Copy link
Member

What build tools are you using (it would help to see your configs as well)?

@mattxyzeth
Copy link

mattxyzeth commented Feb 27, 2022

The same thing happened to me. I'm using typescript with jest Node 16 lts.

"devDependencies": {
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.3",
    "@testing-library/user-event": "^14.0.0-beta",
    "jest": "^27.5.1",
    "ts-jest": "^27.1.3",
    "ts-node": "^10.5.0"
}
{
  "compilerOptions": {
    "allowUmdGlobalAccess": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUnusedParameters": false,
    "noUnusedLocals": true,
    "skipLibCheck": true,
    "moduleResolution": "node",
    "removeComments": true,
    "target": "ESNEXT",
    "module": "ESNext",
    "noEmit": true,
    "esModuleInterop": true,
    "jsx": "react"
  },
  "include": ["src"]
}
export default {
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8",
  preset: 'ts-jest/presets/default-esm',
  testEnvironment: 'jest-environment-jsdom',
  transform: {},
  transformIgnorePatterns: [
    "node_modules/(?!(ts-invariant)/)",
  ],
  extensionsToTreatAsEsm: [
    ".jsx",
    ".ts",
    ".tsx"
  ],
  globals: {
    'ts-jest': {
      useESM: true
    },
  },
  setupFilesAfterEnv: ['./jest.setup.ts']
};
import userEvent from '@testing-library/user-event'

const user = userEvent.setup()

error: TypeError: userEvent.setup is not a function

If I run console.log(userEvent) I get { PointerEventsCheckLevel: [Getter], default: [Getter] }

I can access the methods if I access them through default but typescript thinks userEvent is already the default. Very weird.

@mattxyzeth
Copy link

Strangely enough, this issue is not present on my private CI runner I'm running on EC2. So it seems to be related to my local environment. I'm using .nvmrc so my node install should be the same. I'm not using different build/test tooling in the CI so I'm not sure what is different.

@ph-fritsche
Copy link
Member

ph-fritsche commented Mar 1, 2022

The import works just fine in node locally and on Stackblitz:
https://stackblitz.com/edit/node-ndptdu?file=index.mjs

@mattxyzeth Could you check if this works in both of your environments outside of the test runner?
We need to make sure this is not a misconfiguration of the transpiler.

Also please have a look at this: #757 (comment)

@mattxyzeth
Copy link

I'll try to test this out soon. Just a quick note, the stackblitz you posted isn't using typescript. My problem is definitely a configuration issue but I can't seem to figure out what is configured wrong. No matter what I try my import is always coming from the .cjs file. Even though I've explicitly declared my project as a module and have all the configuration in jest and TS to compile as a module. I'm not convinced this is a testing-library issue but you guys should definitely know about it.

@timdeschryver
Copy link
Member

Could you create a reproduction please?
FWIW, the latest version (previous version too) seems to be working in combination with TypeScript in the Angular Testing Library - testing-library/angular-testing-library#283

@mattxyzeth
Copy link

mattxyzeth commented Mar 17, 2022 via email

@eps1lon
Copy link
Member

eps1lon commented Mar 18, 2022

import userEvent from '@testing-library/user-event'; imports the default export of user-event as userEvent. However, that package has no default export. Only named exports. What you probably want is

-import userEvent from '@testing-library/user-event';
+import * userEvent from '@testing-library/user-event';

@ph-fritsche
Copy link
Member

ph-fritsche commented Mar 18, 2022

This is the ESM export by esbuild:
https://unpkg.com/browse/@testing-library/user-event@14.0.0-beta.13/dist/index.mjs

2966 | var userEvent = __spreadProps(__spreadValues({}, directApi_exports), {
2967 |   setup: setupMain
2968 | });
2969 | export {
2970 |   PointerEventsCheckLevel,
2971 |   userEvent as default
2972 | };

@eps1lon
Copy link
Member

eps1lon commented Mar 18, 2022

Oh we're talking about the beta. The latest stable didn't have a ESM entrypoint specified in the package.json so I was confused.

Can't say why this is happening in the beta without a repro.

@ph-fritsche ph-fritsche added the needs investigation Someone has to do research on this label Mar 24, 2022
@jahumes
Copy link

jahumes commented Mar 25, 2022

Could this be related to jestjs/jest#12120? I am running typescript and ts-jest and the import is index.cjs?

@ph-fritsche ph-fritsche removed this from the userEvent v14 milestone Mar 29, 2022
@capndave
Copy link

capndave commented Apr 5, 2022

Same issue, but with any of the userEvent methods

@sherodtaylor
Copy link

same issue getting _userEvent.default.click is not a function with jest

jsdom fourteen w/ jest react-scripts

     "react": "^16.12.0",
     "react-scripts": "^3.4.1",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^12.1.3",
    "@testing-library/react-hooks": "^7.0.2",
    "@testing-library/user-event": "^14.0.4",

@sherodtaylor
Copy link

Any update on this?

@strmer15
Copy link

This happened to me today with @testing-library/user-event 14.1.0 with Typescript 4.6.3, Jest 27.5.1 and TS Jest 27.1.4 (latest version of each).

What I found was that this happened in my project because the files in the dist folder of the package are produced with .cjs and .mjs extensions. When I renamed them to use .js, moved the ESM entry point into a separate esm directory, and then updated the package.json paths, everything worked again for me.

Here's the patch file I created locally:

diff --git a/node_modules/@testing-library/user-event/dist/index.mjs b/node_modules/@testing-library/user-event/dist/esm/index.js
similarity index 100%
rename from node_modules/@testing-library/user-event/dist/index.mjs
rename to node_modules/@testing-library/user-event/dist/esm/index.js
diff --git a/node_modules/@testing-library/user-event/dist/index.cjs b/node_modules/@testing-library/user-event/dist/index.js
similarity index 100%
rename from node_modules/@testing-library/user-event/dist/index.cjs
rename to node_modules/@testing-library/user-event/dist/index.js
diff --git a/node_modules/@testing-library/user-event/package.json b/node_modules/@testing-library/user-event/package.json
index 9d8bdc0..35134cb 100644
--- a/node_modules/@testing-library/user-event/package.json
+++ b/node_modules/@testing-library/user-event/package.json
@@ -25,12 +25,12 @@
   "files": [
     "dist"
   ],
-  "main": "./dist/index.cjs",
-  "module": "./dist/index.mjs",
+  "main": "./dist/index.js",
+  "module": "./dist/esm/index.js",
   "exports": {
     ".": {
-      "require": "./dist/index.cjs",
-      "default": "./dist/index.mjs"
+      "require": "./dist/index.js",
+      "default": "./dist/esm/index.js"
     }
   },
   "types": "./dist/types/index.d.ts",

@JimLin94
Copy link

JimLin94 commented Apr 22, 2022

I came across the same issue too.
The temporary solution for me is I added the support type cjs to the transform configs of Jest in the package.json

jest: {
  ...,
  "transform": {
-   "^.+\\.(js|jsx)$": "babel-jest",
+   "^.+\\.(js|jsx|cjs)$": "babel-jest",
  }
}

@DominicTylor
Copy link

For me works after add:

transformIgnorePatterns: [
        '/node_modules/(?!(react-use)/)',
],

@martenmatrix
Copy link

martenmatrix commented May 18, 2022

I just had to update to the latest version:
npm install @testing-library/user-event@latest

@indgomez
Copy link

hello, i have the same problem and i have already tried with version 14 and 13.5.0 of @testing-library/dom/user-event
TypeError: userEvent.upload is not a function

@sbland
Copy link

sbland commented Jun 14, 2022

This happened to me today with @testing-library/user-event 14.1.0 with Typescript 4.6.3, Jest 27.5.1 and TS Jest 27.1.4 (latest version of each).

What I found was that this happened in my project because the files in the dist folder of the package are produced with .cjs and .mjs extensions. When I renamed them to use .js, moved the ESM entry point into a separate esm directory, and then updated the package.json paths, everything worked again for me.

Here's the patch file I created locally:

diff --git a/node_modules/@testing-library/user-event/dist/index.mjs b/node_modules/@testing-library/user-event/dist/esm/index.js
similarity index 100%
rename from node_modules/@testing-library/user-event/dist/index.mjs
rename to node_modules/@testing-library/user-event/dist/esm/index.js
diff --git a/node_modules/@testing-library/user-event/dist/index.cjs b/node_modules/@testing-library/user-event/dist/index.js
similarity index 100%
rename from node_modules/@testing-library/user-event/dist/index.cjs
rename to node_modules/@testing-library/user-event/dist/index.js
diff --git a/node_modules/@testing-library/user-event/package.json b/node_modules/@testing-library/user-event/package.json
index 9d8bdc0..35134cb 100644
--- a/node_modules/@testing-library/user-event/package.json
+++ b/node_modules/@testing-library/user-event/package.json
@@ -25,12 +25,12 @@
   "files": [
     "dist"
   ],
-  "main": "./dist/index.cjs",
-  "module": "./dist/index.mjs",
+  "main": "./dist/index.js",
+  "module": "./dist/esm/index.js",
   "exports": {
     ".": {
-      "require": "./dist/index.cjs",
-      "default": "./dist/index.mjs"
+      "require": "./dist/index.js",
+      "default": "./dist/esm/index.js"
     }
   },
   "types": "./dist/types/index.d.ts",

Slightly more edge case example. Using the UserEvent library in a bit.dev component had the same issue. I followed the steps above but what actually worked was moving the index.cjs file out of the dist to the same level as the package.json file and renaming it to index.js.

@alessandrocapra
Copy link

Also experiencing the same issue (just tried to update to latest), reverting to v13 for the moment until it's solved.

@ph-fritsche
Copy link
Member

It seems that the current export - although it shouldn't - does still cause problems in some environments.

Would you please check out this
alternative build of v14.2.3
and report per reaction (:tada: = works, :confused: = does not work) on this comment if it works in your environment?

# yarn 1
yarn add https://pkg.csb.dev/testing-library/user-event/commit/5a1941e1/@testing-library/user-event
# yarn 2, 3
yarn add @testing-library/user-event@https://pkg.csb.dev/testing-library/user-event/commit/5a1941e1/@testing-library/user-event/_pkg.tgz
# npm
npm i https://pkg.csb.dev/testing-library/user-event/commit/5a1941e1/@testing-library/user-event

@Tommoore96
@laurmurclar @cwgw @creimers @wencel @k-sav @bijay-ps @JohnKearney2020 @FiveTies @jahumes @cblaine @headquarters @Joroze @AdamMescher @dimadk24 @litzebauer @Joblyn @suellenx @baNROne @MFukazawa @cedricmatalog @marcusvalverde @kokiy @johnshift @sbland @miphe
@mattxyzeth @capndave @sherodtaylor @strmer15 @JimLin94 @DominicTylor @indgomez @alessandrocapra

@KutanaDev
Copy link

The alternative build package changed the error to TypeError: target.ownerDocument.createRange is not a function

@ph-fritsche
Copy link
Member

@KutanaDev See #902 (comment)

@ramonaspence
Copy link

ramonaspence commented Jul 21, 2022

I had the same error.

@testing-library/user-event version 14.3

Tried this test just to get it up and running:

test('inputing username updates state', () => {
        const user = userEvent.setup()
        render(<Login />);
        
        user.type(screen.getByPlaceholderText(/username/i),
            {target: {value: 'Text'}});
        expect(screen.getByDisplayValue(/Text/)).
        toBeInTheDocument()
    });

My error:
_userEvent.default.setup is not a function

Would you please check out this
alternative build of v14.2.3
and report per reaction (🎉 = works, 😕 = does not work) on this comment if it works in your environment?

This build seems to have solved the error I was getting.

I don't want to react to the comment since I'm not any of the people tagged.

@ph-fritsche
Copy link
Member

@ramonaspence Thanks for the feedback. I just tagged the people who upvoted the issue or commented that they are affected. I'm happy if someone else is following this conversation and adds a reaction. ;)

@melan0802
Copy link

I got same problem, here is my situation:

  1. typeof userEvent = string; userEvent = index.cjs;
  2. In jest.config.transform I got "^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
  3. fileTransform.js:
'use strict';

const path = require('path');

// This is a custom Jest transformer turning file imports into filenames.
// http://facebook.github.io/jest/docs/en/webpack.html

module.exports = {
  process(src, filename) {
    return `module.exports = ${JSON.stringify(path.basename(filename))};`;
  },
};

It's clearly .cjs/.mjs file was trasformed to it's filename, so I fix this by adding mjs and cjs into "^(?!.*\\.(mjs|cjs|js|jsx|css|json)$)".

Maybe most problems which package is index.js were caused by jest.config.transform.

franzheidl added a commit to sapcc/juno that referenced this issue Jul 28, 2022
The test currently fails due to a bug in react testing libarary (testing-library/user-event#839). Once this is resolved the test can be activated and should work
edda pushed a commit to sapcc/juno that referenced this issue Jul 28, 2022
* [ui] CodeBlock: add tabbed codeblocks

* [ui] CodeBlock: add tests for tabbed codeblock

* [ui] Codeblock: remove obsolete, adjust styles

* [ui] CodeBlock: add disabled test for copy to clipboard

The test currently fails due to a bug in react testing libarary (testing-library/user-event#839). Once this is resolved the test can be activated and should work
@ph-fritsche ph-fritsche removed the needs investigation Someone has to do research on this label Aug 1, 2022
@github-actions
Copy link

github-actions bot commented Aug 2, 2022

🎉 This issue has been resolved in version 14.4.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@edmundsj
Copy link

edmundsj commented Oct 5, 2022

I am encountering the same exact issue on 14.4.3.

I am trying to install user-event using the install instructions available here and then call userEvent.setup() per the instructions here.

To Reproduce Steps to reproduce the behavior:

  1. Use create-react-app to make a new project: npx create-react-app .
  2. Install user-event, react testing library and testing library DOM: npm install --save-dev @testing-library/react @testing-library/dom @testing-library/user-event
  3. Attempt to import userEvent: import {userEvent} from '@testing-library/user-event';
  4. Run the test and get the following error:
Cannot read property 'setup' of undefined
TypeError: Cannot read property 'setup' of undefined

Expected behavior

I expect, on installing @testing-library/user-event to be able to import userEvent and have it be defined. It is not.

Screenshots If applicable, add screenshots to help explain your problem.
My full test file:

import { render, screen } from '@testing-library/react';
import App from './App';
import {userEvent} from '@testing-library/user-event';

test('renders learn react link', () => {
  const user = userEvent.setup()
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

Default App.js:

import logo from './logo.svg';
import './App.css';


function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

Desktop (please complete the following information):

  • OS: Ubuntu 22.04
  • Browser: None (Jest runner)
  • Version: 14.4.3 (user-event)

Additional context
I'm following the same pattern I used to install all my other npm modules, and have only been using this library for the last 2 days. The fact that I can't even import a module out of the box that's referred to in the docs seems weird. If I'm importing it from the wrong location it's because the examples in the docs do not have an explicit "import" statement to access the userEvent object.

@NicolasBonzini
Copy link

I just had to update to the latest version: npm install @testing-library/user-event@latest
This works for me.Thanks!

@MuKhAlt
Copy link

MuKhAlt commented Dec 3, 2022

I just had to update to the latest version: npm install @testing-library/user-event@latest
This works for me.Thanks!

This solved it for me, thank you!

@stephen-hopkins
Copy link

I was having the same issue on 14.4.3 but importing it as follows works:

import * as userEvent from "@testing-library/user-event";

const user = userEvent.default.setup();

@jtomaszewski
Copy link

In my case it's even different, it seems that the only following version is working:

import userEvent from "@testing-library/user-event";

const user = userEvent.default.setup();

FYI I'm using typescript 5.1.6 with moduleResolution: "nodenext" and esm modules.

@stefannibrasil
Copy link

stefannibrasil commented Jan 4, 2024

Here's what worked for me:

import React from 'react'
import {render, screen} from '@testing-library/react'
import userEvent from "@testing-library/user-event"
import {FavoriteNumber} from '../favorite-number'

describe('when the number input is invalid', () => {
  test('displays an error message', () => {
    // const user = userEvent.default.setup(); <---- not needed
    render(<FavoriteNumber />)
    const input = screen.getByLabelText(/favorite number/i)

    userEvent.type(input, '10') // <----- calling userEvent.type()

    expect(screen.getByRole('alert')).toHaveTextContent(
      /the number is invalid/i,
    )
  })
})

These are my dependencies:

"dependencies": {
    "@reach/router": "^1.3.4",
    "@testing-library/dom": "^7.28.1",
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/react": "^11.2.2",
    "@testing-library/react-hooks": "^3.4.2",
    "@testing-library/user-event": "^12.4.0",
    "history": "^5.0.0",
    "jest": "^26.6.3",
    "jest-axe": "^4.1.0",
    "kcd-scripts": "^7.5.1",
    "msw": "^0.24.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-redux": "^7.2.2",
    "react-router": "^5.2.0",
    "react-router-dom": "^5.2.0",
    "react-test-renderer": "^17.0.1",
    "react-transition-group": "^4.4.1",
    "redux": "^4.0.5",
    "test-data-bot": "^0.8.0",
    "whatwg-fetch": "^3.5.0"
  },

@fayez-nazzal
Copy link

I had a migration from cjs to esm, userEvent started didn't work anymore. A solution worked well for me is to add this to setupTests.ts:

import userEvent from'@testing-library/user-event';

jest.unstable_mockModule('@testing-library/user-event', () => ({
  default: userEvent.default,
}));

Then it worked normally without any more changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet