doritoslover
doritoslover

Reputation: 121

Jest unit test ReferenceError: React is not defined

I've been working on an ASP.Net core application where I have added React components. I've been trying to add React unit tests and it's been real challenging but I feel like I'm getting close. The latest error I'm getting is "ReferenceError: React is not defined" when executing npm test.

I added "import React from 'react';" at the top of my jsx file and the test executed fine. The problem is when I try run my application, I now get:

Uncaught TypeError: Failed to resolve module specifier "react". Relative references must start with either "/", "./", or "../".

Coming from a .NET background, I'm not used to having to install a whole bunch of third party packages to get things working. I'm probably missing something.

import React from 'react';    //This causes an error in my application but fixes my unit test error

export class MyReactComponent extends React.Component {    
...
}

import { MyReactComponent } from "../wwwroot/src/react/myReactComponent.jsx"
import { render } from '@testing-library/react';

describe("Test", () => {
    it("myTest", () => {                
        render(<MyReactComponent />);       
    });
});

package.json

 {
      "name": "bs.bsw1.portal",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "dependencies": {
        "@microsoft/signalr": "^6.0.8",
        "dotenv": "^10.0.0",
        "nodejs": "^0.0.0",
        "react": "^18.0.0",
        "react-dom": "^18.2.0"
      },
      "devDependencies": {
        "@babel/core": "^7.17.10",
        "@babel/preset-env": "^7.17.10",
        "@babel/preset-react": "^7.18.6",
        "@testing-library/dom": "^8.17.1",
        "@testing-library/jest-dom": "^5.16.5",
        "@testing-library/react": "^13.3.0",
        "@testing-library/user-event": "^14.4.3",
        "@types/mocha": "^9.1.1",
        "@types/node": "^18.7.5",
        "jest": "^28.1.3",
        "jest-editor-support": "^30.1.0",
        "jest-environment-jsdom": "^28.1.3",
        "mocha": "8.3.0"
      },
      "scripts": {
        "test": "jest --verbose ./__tests__"
      },
      "jest": {
        "testEnvironment": "jsdom"
      },
      "author": "",
      "license": "ISC",
      "type": "module"
    }

babel.config.cjs

module.exports = {
    presets: [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "10"
                }
            }               
        ],
        ["@babel/preset-react", {
          "runtime": "automatic"
       }]
    ]   
};

Any help would be much appreciated!

Upvotes: 1

Views: 4241

Answers (0)

Related Questions