I am having an error when I build my application in react. I noticed this error only when I tried to build application.
When I stopped dev server and ran it again, it showed the same error. It seems that I made some change that only showed when I started the server again or make build:
Module not found: Error: Can't resolve 'buffer' in '\node_modules\htmlparser2\lib' BREAKING CHANGE: webpack < 5
used to include polyfills for node.js core modules by default.This is
no longer the case. Verify if you need these module and configure a
polyfill for it.
If you want to include a polyfill, you need to install 'buffer'. If
you don't want to include a polyfill, you can use an empty module like
this:
resolve.alias: { "buffer": false }
error Command failed with exit code 1.
My application is made in CRA and Typescript. This is my package.json:
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "react-scripts start",
"build": "cross-env NODE_OPTIONS='--max-old-space-size=4096' react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"dependencies": {
"#apollo/react-hooks": "^4.0.0",
"#date-io/moment": "^1.3.13",
"#material-ui/core": "^4.11.0",
"#material-ui/icons": "^4.9.1",
"#material-ui/lab": "^4.0.0-alpha.56",
"#material-ui/pickers": "^3.2.10",
"#optimizely/react-sdk": "^2.4.0",
"apollo-boost": "^0.4.9",
"classnames": "^2.2.6",
"formik": "^2.2.5",
"graphql": "^15.4.0",
"lodash": "^4.17.20",
"moment": "^2.29.1",
"react": "^16.13.1",
"react-app-polyfill": "^2.0.0",
"react-dom": "^16.13.1",
"react-google-recaptcha": "^2.1.0",
"react-masonry-css": "^1.0.14",
"react-router-dom": "^5.2.0",
"react-test-renderer": "^16.13.1",
"react-toastify": "^6.1.0",
"reset-css": "^5.0.1",
"use-debounce": "^5.1.0"
},
"devDependencies": {
"#testing-library/jest-dom": "^5.11.6",
"#testing-library/react": "^11.2.1",
"#testing-library/user-event": "^12.2.2",
"#types/classnames": "^2.2.11",
"#types/enzyme": "^3.10.8",
"#types/enzyme-adapter-react-16": "^1.0.6",
"#types/jest": "^26.0.15",
"#types/lodash": "^4.14.165",
"#types/moment": "^2.13.0",
"#types/node": "^14.14.9",
"#types/react": "^16.9.56",
"#types/react-dom": "^16.9.9",
"#types/react-google-recaptcha": "^2.1.0",
"#types/react-router-dom": "^5.1.6",
"cross-env": "^7.0.2",
"enzyme": "^3.11.0",
"enzyme-adapter-react-16": "^1.15.5",
"enzyme-to-json": "^3.6.1",
"husky": "^4.3.0",
"jest-dom": "^4.0.0",
"jest-sonar-reporter": "^2.0.0",
"lint-staged": "^10.5.1",
"node-sass": "^5.0.0",
"prettier": "^2.2.0",
"ts-jest": "^26.4.4",
"typescript": "^4.1.2"
}
}
You need to install the buffer package
npm install buffer
You have to Install this
npm install assert browserify-zlib buffer process stream-browserify util .
it will help you out
I found a solution to my problem. It is a bit weird that it didn't show up as test error.
SOLUTION
To solve this I just replaced location of TEST_ID to be in my component, and that my-component.test file to import it from there:
My component
import React, { FunctionComponent } from 'react';
/* Tests */
export const TEST_ID = 'my-component-test-id';
export const MyComponent: FunctionComponent = () => {
return <div data-test-id={TEST_ID}>123</div>;
};
Test
import React from 'react';
import { cleanup } from '#testing-library/react';
import { mount } from 'enzyme';
import { TEST_ID } from './my-component';
import MyComponent from './my-component'
afterEach(cleanup);
it('Render My component and have some value', () => {
const wrapper = mount(<MyComponent />);
const myComponent = wrapper.find(`[data-testid='${TEST_ID}']`);
expect(myComponent).toHaveValue('some value');
});
Analysis
Apparently if you import some value (in my case a constant) from .test file, if you try and build your app, the mentioned error will show up.
In my case I had a component:
MyComponent
import React, { FunctionComponent } from 'react';
/* Tests */
import { TEST_ID } from './test/my-component.test';
export const MyComponent: FunctionComponent = () => {
return <div data-test-id={TEST_ID}>some value</div>;
};
The TEST_ID was imported from my-component.test file. The purpose of that constant was to have that test id set for component so I can find that element based of that test id in my test.
Test
import React from 'react';
import { cleanup } from '#testing-library/react';
import { mount } from 'enzyme';
import MyComponent from './my-component'
afterEach(cleanup);
export const TEST_ID = 'my-component-test-id';
it('Render My component and have some value', () => {
const wrapper = mount(<MyComponent />);
const myComponent = wrapper.find(`[data-testid='${TEST_ID}']`);
expect(myComponent).toHaveValue('some value');
});
you need to install 'buffer' : npm install buffer oR npm install buffer --f
Related
I have a working nextjs app and am wanting to add Cypress component tests for my react components.
e2e cypress tests are working without issue, but when trying to implement component tests I'm receiving the error, "Cannot read properties of undefined (reading 'displayName')" when trying to mount a component.
I followed the documentation at https://docs.cypress.io/guides/component-testing/component-framework-configuration#Next-jsn and also accepted the configuration that was generated by the cypress tool when I ran yarn cypress.
My code with component testing issue is at https://gitlab.com/kennyrbr/activ/-/tree/cypress-testing/web
Here is where I'm attempting to mount .
import React from 'react';
import { mount } from '#cypress/react';
import { NavBar } from '../../components/NavBar';
describe('NavBar.cy.ts', () => {
it('playground', () => {
cy.mount(`<NavBar />`);
});
});
My package.json is
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"gen": "graphql-codegen --config codegen.yml",
"cypress": "cypress open"
},
"dependencies": {
"#graphql-codegen/typescript-urql": "^3.6.1",
"#urql/exchange-graphcache": "^4.4.3",
"daisyui": "^2.22.0",
"formik": "^2.2.9",
"graphql": "^16.5.0",
"next": "latest",
"next-urql": "^3.3.3",
"react": "18.1.0",
"react-dom": "18.1.0",
"react-is": "^18.2.0",
"urql": "^2.2.2",
"yup": "^0.32.11"
},
"devDependencies": {
"#cypress/react": "^6.1.1",
"#cypress/webpack-dev-server": "^2.2.0",
"#graphql-codegen/cli": "^2.8.0",
"#graphql-codegen/typescript": "^2.7.1",
"#graphql-codegen/typescript-operations": "^2.5.1",
"#testing-library/cypress": "^8.0.3",
"#types/node": "17.0.35",
"#types/react": "18.0.9",
"#types/react-dom": "18.0.5",
"autoprefixer": "^10.4.7",
"cypress": "^10.6.0",
"html-webpack-plugin": "^5.5.0",
"postcss": "^8.4.14",
"tailwindcss": "^3.1.2",
"typescript": "4.7.2",
"webpack": "^5.74.0",
"webpack-dev-server": "^4.10.0"
}
}
Here's the error which displays after running yarn cypress and choosing component testing for the 'NavBar.cy.ts' test.
N.B., I did add a few dev dependencies because I was receiving a webpack warning early on.
Any help is greatly appreciated.
edit:
I had added an incorrect displayName assignment to some of my components in an attempt to get cypress component testing working - and had forgotten to remove in a previous commit. This wasn't even the issue as displayName couldn't be read from undefined, so I think the issue is that the component/s aren't available to cypress. In any case, it was wrong and I've removed.
The basic problem is the parameter you are passing into cy.mount() isn't being compiled to JSX.
Two things should fix it
take the quotes off the JSX, so it should be cy.mount(<NavBar />);
change the extension of the spec file to NavBar.cy.tsx
It's not really a working nextjs app, you are getting the exact same message from a different component SelectActivType.tsx when you you run the app (outside of the Cypress test).
In terms of the NavBar, the code should be adjusted from this
export const NavBar: React.FC<NavBarProps> = ({}) => {
NavBar.displayName = 'ActivTypes';
const router = useRouter();
return (
...
);
}
to this
export const NavBar: React.FC<NavBarProps> = ({}) => {
const router = useRouter();
return (
...
);
}
// move the offending line outside of the function
NavBar.displayName = 'ActivTypes';
You cannot add a property to a function inside the function definition.
For reference see how to set displayName in a functional component [React].
I am trying to test my application.
The test that I am trying to run, has as objective to test a thunk function (redux toolkit).
I am also using Firebase for authentication and Firestore for storage.
I have this error in console.
Jest encountered an unexpected token
/home/fml/Escritorio/Projects/Journal-app/node_modules/firebase/app/dist/index.esm.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { registerVersion } from '#firebase/app';
^^^^^^
SyntaxError: Cannot use import statement outside a module
> 1 | import { FirebaseOptions, initializeApp } from 'firebase/app';
| ^
2 | import { getAuth } from 'firebase/auth';
3 | import { getFirestore } from 'firebase/firestore/lite';
4 | import { getEnvironments } from '../utils';
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (src/firebase/config.ts:1:1)
This is the test I am trying to run. I am trying to mock my providers file, which consists of Firebase authentication methods, but it doesn't seem to work.
import { checkingCredentials } from '../../../src/redux/auth/authSlice';
import { checkingAuthentication } from '../../../src/redux/auth/thunk';
jest.mock('../../../src/firebase/providers');
describe('thunk.ts (auth)', () => {
const dispatch = jest.fn();
beforeEach( () => jest.clearAllMocks() );
test('should invoke checkingCredentials', async() => {
await checkingAuthentication()( dispatch );
expect( dispatch ).toHaveBeenCalledWith( checkingCredentials() )
});
});
This is my jest config (jest.config.ts):
export default {
testEnvironment: "jsdom",
transform: {
"^.+\\.tsx?$": "ts-jest"
},
moduleNameMapper: {
'\\.(css|less|sass|scss)$': 'identity-obj-proxy',
},
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
transformIgnorePatterns: [],
}
This is my jest setup (jest.setup.ts):
import 'setimmediate';
import 'whatwg-fetch';
import { config } from 'dotenv';
config({
path: '.env'
});
jest.mock('./src/utils/getEnvironments', () => ({
getEnvironments: () => ({ ...process.env })
}));
Main Stack:
Vite JS: 2.9.9
React JS: 18.0.0
TypeScript: 4.6.3
Firebase: 9.8.3
reduxjs/toolkit: 1.8.2
These are my installed dependencies
{
"name": "journal-app",
"private": true,
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "jest --verbose=true"
},
"dependencies": {
"#cloudinary/react": "^1.4.1",
"#cloudinary/url-gen": "^1.8.0",
"#lottiefiles/react-lottie-player": "^3.4.7",
"#reduxjs/toolkit": "^1.8.2",
"firebase": "^9.8.3",
"react": "18.0.0",
"react-dom": "18.0.0",
"react-hot-toast": "^2.2.0",
"react-icons": "^4.4.0",
"react-redux": "^8.0.2",
"react-router-dom": "^6.3.0"
},
"devDependencies": {
"#testing-library/react": "^13.3.0",
"#types/jest": "^28.1.2",
"#types/react": "18.0.0",
"#types/react-dom": "18.0.0",
"#types/react-redux": "^7.1.24",
"#vitejs/plugin-react": "1.3.0",
"autoprefixer": "10.4.7",
"cloudinary": "^1.30.0",
"daisyui": "2.15.4",
"dotenv": "^16.0.1",
"identity-obj-proxy": "^3.0.0",
"jest": "^28.1.1",
"jest-environment-jsdom": "^28.1.1",
"postcss": "8.4.14",
"setimmediate": "^1.0.5",
"tailwindcss": "3.1.3",
"ts-jest": "^28.0.5",
"ts-node": "^10.8.1",
"typescript": "4.6.3",
"vite": "2.9.9",
"whatwg-fetch": "^3.6.2"
}
}
How can I mock my file or how can I test the thunk function?
I have nextjs app + typescript + react-leaflet
when I start my development server npm run dev it's fine there is no error,
but when I start build with npm run build I have an error, it says.
Type error: Module '"react-leaflet"' has no exported member 'useEventHandlers'.
1 | import { useMemo, useCallback, useState } from 'react'
> 2 | import { useMap, useMapEvent, useEventHandlers, MapContainer } from 'react-leaflet'
| ^
3 |
4 | // Classes used by Leaflet to position controls
5 | const POSITION_CLASSES = {
info - Checking validity of types .
Here's my package.json file.
{
"name": "spot-nearby",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"#types/leaflet": "^1.7.0",
"#types/react-leaflet": "^2.8.1",
"axios": "^0.21.1",
"csv-parser": "^3.0.0",
"leaflet": "^1.7.1",
"leaflet-geosearch": "^3.3.2",
"next": "10.2.3",
"papaparse": "^5.3.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-leaflet": "^3.2.0",
"react-leaflet-search": "^2.0.1",
"react-loader-spinner": "^4.0.0",
"react-papaparse": "^3.14.0",
"react-search-field": "^1.2.1"
},
"devDependencies": {
"#types/react": "17.0.8",
"typescript": "4.3.2"
}
}
I already install #types/react-leaflet, but why did this happened?
react-leaflet in fact does not export useEventHandlers method. It's a method from #react-leaflet/core package. It's a dependency of react-leaflet package and must be installed along with it. And should be imported from there:
import { useMap, useMapEvent, MapContainer } from 'react-leaflet'
import { useEventHandlers } from '#react-leaflet/core'
I've got a TypeScript function which returns a React Native View.
import React from "react";
import JSX, {View} from "react-native";
class DummyClass {
static getView() {
return (
<View style={{flex: 1}}/>
);
}
}
export default DummyClass;
And I'm calling this function in this way:
import JSX from "react-native";
import DummyClass from "./util/dummy";
const DummyWrapper = () => {
return (DummyClass.getView());
};
export default DummyWrapper;
And when I run eslint, I get a warning.
5:5 warning Missing return type on function #typescript-eslint/explicit-module-boundary-types
So, I need to be returning something. JSX.Element seems reasonable enough, but that doesn't seem to be working. For one, when I try to return a JSX.Element, VSCode can't resolve it and pretends it's any instead. And moreover, it causes errors in other places that call the function.
So, doing this:
static getView() : JSX.Element {
and const DummyWrapper = () : JSX.Element => {
Results in the following error in DummyCaller:
5:5 error Unsafe return of an any typed value #typescript-eslint/no-unsafe-return
So now I'm not sure exactly what to do. I've tried a few other things, such as returning View, typeof View, React.Component (and typeof), and a few other things. I've also messed around with where JSX is being imported from. If I import from react, it seems to work even worse than if I import it from react-native. Also in my research, I see the most common problem is that one's React and React Native types are out of date, but as far as I can tell, I'm on the most up-to-date versions.
My packages.json:
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject",
"lint": "eslint -c .eslintrc.js --ext .tsx ."
},
"dependencies": {
"#dudigital/react-native-zoomable-view": "^1.0.15",
"#react-native-community/masked-view": "^0.1.10",
"#react-navigation/native": "^5.7.6",
"#react-navigation/stack": "^5.9.3",
"#types/react-native-vector-icons": "^6.4.6",
"change-case": "^4.1.1",
"expo": "~39.0.2",
"expo-status-bar": "~1.0.2",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-39.0.2.tar.gz",
"react-native-gesture-handler": "^1.8.0",
"react-native-paper": "^4.2.0",
"react-native-reanimated": "^1.13.1",
"react-native-safe-area-context": "^3.1.8",
"react-native-screens": "^2.11.0",
"react-native-tab-view": "^2.15.2",
"react-native-vector-icons": "^7.1.0",
"react-native-web": "^0.13.18"
},
"devDependencies": {
"#babel/core": "~7.9.0",
"#types/jest": "^26.0.15",
"#types/react": "^16.9.53",
"#types/react-dom": "^16.9.8",
"#types/react-native": "^0.63.27",
"#types/react-navigation": "^3.4.0",
"#types/react-redux": "^7.1.9",
"#types/react-test-renderer": "^16.9.3",
"#typescript-eslint/eslint-plugin": "^4.5.0",
"#typescript-eslint/parser": "^4.5.0",
"commonjs": "latest",
"eslint": "^7.11.0",
"eslint-plugin-jsdoc": "^30.7.3",
"eslint-plugin-prefer-arrow": "^1.2.2",
"eslint-plugin-react": "^7.21.5",
"react-native-typescript-transformer": "^1.2.13",
"requirejs": "latest",
"ts-jest": "^26.4.1",
"tslib": "^2.0.3",
"typescript": "^4.0.3"
},
"private": true
}
React should be putting JSX into the global namespace, so if you don't import it from anywhere then returning JSX.Element should work.
You can also import {ReactElement} from "react" and return ReactElement.
You can also import {FunctionComponent} from "react" and type the DummyWrapper function itself, not the return type, as DummyWrapper: FunctionComponent<{}>.
There's a lot of options.
But I really do not understand the use case where you would be creating an element from a static method on a class. This seems like a bad design that you should rethink. Can you make getView into a function component? Do you need the class DummyClass at all?
I wanna run unit test at react, but when I run "npm test", it shows me this error:
navList.test.js: Unexpected token (12:26)
> 12 | let app = shallow(<NavList/>);
| ^
Following is my code:
navList.test.js
import React from 'react';
import {shallow, configure} from 'enzyme';
import {expect} from 'chai';
import {NavList} from '../components/common/nav/navList';
import Adapter from 'enzyme-adapter-react-16';
configure({adapter: new Adapter()});
describe('NavList', function () {
it('NavList ', function () {
let app = shallow(<NavList/>);
expect(app.find('h2').length).to.equal(1);
});
});
package.json:
"scripts": {
"test": "jest"
},
"devDependencies": {
"axios": "^0.16.2",
"babel-jest": "^22.1.0",
"babel-preset-react": "^6.23.0",
"bootstrap": "^4.0.0-beta",
"bootstrap-sass": "^3.3.7",
"chai": "^4.1.2",
"cross-env": "^5.0.1",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"jest": "^22.1.4",
"jquery": "^3.1.1",
"laravel-mix": "^1.0",
"lodash": "^4.17.4",
"mocha": "^5.0.0",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-test-renderer": "^16.2.0"
}
Did I miss something at install ?
It looks like the code isn't getting transpiled before jest is trying to run it (hence the Unexpected token error).
Take a look at the setup instructions here. My best guess is that you need to update your .babelrc with the react preset.