ReferenceError: expect is not defined in react app - javascript

I am developing a react app, suddenly after adding two tests I got an error that is,
ReferenceError: expect is not defined
./node_modules/#testing-library/jest-dom/dist/extend-expect.js
node_modules/#testing-library/jest-dom/dist/extend-expect.js:9
I tried to implement the solutions I found on the internet but nothing is working. Here are my two test files,
1st one,
import React from "react";
import { render, screen, within } from "#testing-library/react";
import Index from "./Index";
describe("<Index/>", () => {
it("checking render", () => {
render(<Index />);
});
});
it("checking text", () => {
const { getByTestId } = render(<Index />);
const { getByText } = within(getByTestId("durbin"));
expect(getByText("DurBinLab-Test")).toBeInTheDocument();
});
And 2nd one is,
import React from "react";
import { render, fireEvent, within, screen } from "#testing-library/react";
import Login from "./Login";
import userEvent from "#testing-library/user-event";
describe("<Login/>", () => {
it("checking render", () => {
render(<Login />);
});
});
it("text check", () => {
const { getByTestId } = render(<Login />);
const { getByText } = within(getByTestId("login"));
expect(getByText("Login")).toBeInTheDocument();
});
describe("Input Field Check", () => {
test("render email input", () => {
render(<Login />);
const inputEl = screen.getByTestId("email-input");
expect(inputEl).toBeInTheDocument();
});
test("pass valid email to test email input field", () => {
render(<Login />);
const inputEl = screen.getByTestId("email-input");
userEvent.type(inputEl, "test#mail.com");
});
Lastly here is my package.json
{
"name": "user-manage",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.4.1",
"#emotion/styled": "^11.3.0",
"#mui/icons-material": "^5.0.0",
"#mui/material": "^5.0.0",
"#testing-library/react": "^12.1.0",
"#testing-library/user-event": "^12.1.10",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-redux": "^7.2.5",
"react-router-dom": "^5.3.0",
"react-scripts": "4.0.3",
"redux": "^4.1.1",
"redux-devtools-extension": "^2.13.9",
"redux-thunk": "^2.3.0",
"uuid": "^3.4.0",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#testing-library/jest-dom": "^5.14.1"
}
}
This is what my JSON file looks like. I tried to edit the setuptest.js file. But the problem is still same.

Related

Error in mapBox when I am deploying react app in Heroku

An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling
I want help to identify this error in production.
The same code is running well in localhost
here is my code
import React, { useRef, useEffect, useState } from 'react';
import 'mapbox-gl/dist/mapbox-gl.css'
import Map, { Marker, MapRef } from "react-map-gl";
import { useDataContext } from './DataContext';
export default function MapView() {
let refs;
// Setting up the state for the map
const [viewport, setViewport] = useState({
latitude: lat,
longitude: lon,
zoom: 10,
bearing: 0,
pitch: 0,
width: "100%",
height: "100%",
attributionControl: false
});
//....more code
return (
<>
<Map
ref={(e) => refs = e}
mapboxAccessToken={process.env.REACT_APP_MAPBOX_KEY}
initialViewState={viewport}
onViewportChange={(viewport) => setViewport(viewport)}
mapStyle={colorThem === 'light' ? 'mapbox://styles/mapbox/dark-v10' : 'mapbox://styles/mapbox/streets-v10'} >
<Marker latitude={lat} longitude={lon}>
<i className="pl-2 fa-solid fa-location-dot fa-bounce text-red-500 text-xl"></i>
</Marker>
</Map>
</>
);
}
The same code is running well in localhost but when I am deploying this on Heroku error only in Mapbox, another feature working properly.
package.json
{
// ....
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.2",
"#testing-library/react": "^12.1.3",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.26.0",
"mapbox-gl": "^2.7.0",
"moment": "^2.29.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-map-gl": "^7.0.7",
"react-moment": "^1.1.1",
"react-scripts": "5.0.0",
"recharts": "^2.1.9",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
//.....
}
see below IMG
error
I solved this problem which is come in production.😊
from ref https://docs.mapbox.com/mapbox-gl-js/guides/install/#:~:text=OR-,defaults%2C%20not%20ie%2011,-This%20can%20be
just changed my package.json browserslist.production field.
this
//....
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
// ...
},
to this
//....
"browserslist": {
"production": [
"defaults",
"not ie 11"
],
// ...
},

SyntaxError: Cannot use import statement outside a module when testing using jest and react-testing-library

I am always getting this error whenever trying to test my file using jest and react-testing-library
error --
Details:
/Users/user/dev/system-wheels/src/Constants/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { MAP_API_KEY } from "../config.local";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-cli/node_modules/jest-runtime/build/index.js:1517:14)
at Object.<anonymous> (node_modules/graceful-fs/polyfills.js:1:99)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.777 s
Ran all test suites matching /Loginpage.test.js/i.
error Command failed with exit code 1.
Here is my package.json-
{
"name": "system-wheels",
"version": "0.1.0",
"private": true,
"dependencies": {
"#firebase/app": "^0.6.29",
"#firebase/messaging": "^0.7.15",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^12.0.0",
"#testing-library/user-event": "^13.2.1",
"prop-types": "^15.7.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-places-autocomplete": "^7.3.0",
"react-redux": "^7.2.2",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"react-window": "^1.8.6",
"redux": "^4.0.5",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"reselect": "^4.0.0",
"storage": "file:./src/Packages/Storage/",
"styled-components": "^5.2.1",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "bash ./scripts/init.sh && react-scripts start",
"build": "bash ./scripts/init.sh && react-scripts build",
"test": "bash ./scripts/init.sh && react-scripts test --transformIgnorePatterns \"node_modules/(?!#toolz/allow-react)/\" --env=jsdom",
"test2": " jest",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"alias": {
"modules": "src/Modules/",
"components": "src/Common/Components/",
"hooks": "src/Hooks/",
"helper": "src/Helper/",
"common": "src/Common/",
"globalStyles": "src/GlobalStyles/",
"constants": "src/Constants/",
"assets": "src/Assets/",
"context": "src/Context/",
"route": "src/Routes/"
},
"devDependencies": {
"#babel/plugin-transform-modules-commonjs": "^7.15.0",
"#babel/plugin-transform-runtime": "^7.15.0",
"#babel/preset-env": "^7.15.0",
"#babel/preset-react": "^7.14.5",
"#babel/runtime": "^7.15.3",
"babel-jest": "^27.1.0",
"jest": "^27.1.0",
"ts-jest": "^27.0.5"
}
}
Here is my - babel.config.js
module.exports = {
presets: [
["#babel/preset-env", { targets: { node: "current" } }],
"#babel/preset-react",
],
};
Here is my - jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "jest-environment-jsdom",
transform: {
"^.+\\.(ts|tsx)?$": "ts-jest",
"^.+\\.(js|jsx)?$": "babel-jest",
},
moduleNameMapper: {
"^constants$": "<rootDir>/src/Constants/",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"^modules(.*)$": "<rootDir>/src/Modules/",
"^helper$": "<rootDir>/src/helper/",
"^context$": "<rootDir>/src/Context/",
"^route(.*)$": "<rootDir>/src/Routes/",
"^assets(.*)$": "<rootDir>/src/Assets/",
"^globalStyles(.*)$": "<rootDir>/src/GlobalStyles/",
"^common(.*)$": "<rootDir>/src/Common/",
"^hooks(.*)$": "<rootDir>/src/Hooks/",
"^components(.*)$": "<rootDir>/src/Common/Components/",
},
};
Here is the unit test
import "#testing-library/jest-dom";
import React from "react";
import { render, fireEvent, waitFor, screen } from "#testing-library/react";
import LoginPage from "../Views/LoginPage";
describe("Login page testing", () => {
let wrapper;
beforeEach(() => {
wrapper = render(<LoginPage />);
});
test("should contain input fields", () => {
screen.getByLabelText("Your Email");
screen.getByLabelText("Password");
});
});
Here is the LoginPage component
import React, { useState, useCallback } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import Form from "./Form";
import { loginUser, updateLoginType } from "../../../Common/ActionCreators";
import useAlert from "../../../Hooks/useAlert";
import Path from "../../../Routes/Path";
import BACK_IMAGE from "../assets/background.png";
import SOFTWARE_IMAGE from "assets/OMS.svg";
import { ViewPortContainer, BackgroundImage, SoftwareLogo } from "../styles";
const { companySelection } = Path.authorized;
const LoginPage = ({ loginUser, history, updateLoginType }) => {
const [inProgress, updateProgress] = useState(false);
const { showAlert } = useAlert();
const navigateToCompanySelectionPage = () => {
history.replace(companySelection.view.path);
};
const onFormSubmit = useCallback(async (values, resetForm) => {
const { login_email, login_password, login_loginAs } = values;
try {
updateProgress(true);
updateLoginType({ isLoggedInAsAdmin: Boolean(login_loginAs) });
await loginUser({
emailOrMobile: login_email.toLowerCase(),
password: login_password,
isAdmin: Boolean(login_loginAs),
});
updateProgress(false);
navigateToCompanySelectionPage();
} catch (err) {
updateProgress(false);
showAlert({ message: err[0], type: "error" });
}
}, []);
return (
<ViewPortContainer>
<SoftwareLogo src={SOFTWARE_IMAGE} />
<BackgroundImage src={BACK_IMAGE} />
<Form onFormSubmit={onFormSubmit} inProgress={inProgress} />
</ViewPortContainer>
);
};
const mapDispatchToProps = (dispatch) =>
bindActionCreators(
{
loginUser,
updateLoginType,
},
dispatch
);
export default connect(null, mapDispatchToProps)(LoginPage);
I am stuck at this problem for days, please Help

how to export component in react js to use in another project?

I make a simple component hello world in react js this
import React from 'react';
function App() {
return (
<div >
hello4
</div>
);
}
export default App;
I export in index file like this
import App from './App'
module.exports = {
App
}
Now I export this component is index.js to use in another project
so in another project I used above project as a dependency like this
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"pubnsi": "git+https://git#github.com/naveennsit/pubs.git",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
but when I used this component in my another project like this it gives me syntax error
import React from 'react';
import './App.css';
import App from "pubnsi/src/App";
function App1() {
return (
<div className="App">
hello
<App/>
</div>
);
}
export default App1;
I tried to replicate this bug in codesandbox
https://codesandbox.io/s/nifty-glitter-bj6sz?file=/package.json
but not getting error in codesandbox.
package.json file
{
"name": "consukmer",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.5.0",
"#testing-library/user-event": "^7.2.1",
"pubnsi": "git+https://git#github.com/naveennsit/pubs.git",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
To use a Github repository as a dependency, you will have to add it like this:
"pubnsi": "naveennsit/pubs"
instead of like this:
"pubnsi": "git+https://git#github.com/naveennsit/pubs.git",

Cannot import createSagaMiddleware from 'redux-saga' in my create-react-app

I have the following import in my create-react-app:
import createSagaMiddleware from 'redux-saga';
Problem is that my system is unable to import createSagaMiddleware.
I am running versions:
node 12.13.0
npm 6.12.1
My package.json looks like this:
{
"name": "foo",
"version": "0.1.0",
"private": true,
"dependencies": {
"firebase": "^7.1.0",
"node-sass": "^4.12.0",
"npm": "^6.12.1",
"react": "^16.10.1",
"react-dom": "^16.10.1",
"react-redux": "^7.1.1",
"react-router-dom": "^5.1.2",
"react-scripts": "3.1.2",
"react-stripe-checkout": "^2.6.3",
"redux": "^4.0.4",
"redux-logger": "^3.0.6",
"redux-persist": "^6.0.0",
"redux-saga": "^1.1.1",
"redux-thunk": "^2.3.0",
"reselect": "^4.0.0",
"styled-components": "^4.4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
My IDE says (Intellij IDEA) says that it 'cannot resolve symbol 'createSagaMiddleware'.
The actual error message that I see is
Error: Actions must be plain objects. Use custom middleware for async actions
which is thrown at
componentDidMount() {
const {fetchCollectionsStart} = this.props;
fetchCollectionsStart();
};
->
const mapDispatchToProps = (dispatch) => ({
fetchCollectionsStart: () => dispatch(fetchCollectionsStart())
});
export default connect(
null,
mapDispatchToProps
)(ShopPage);
The fetchCollectionsStart action looks like this:
import {takeEvery} from 'redux-saga/effects';
import ShopActionTypes from "./shop.types";
export function* fetchCollectionsAsync() {
yield console.log('I am fired');
}
export function* fetchCollectionsStart() {
yield takeEvery(
ShopActionTypes.FETCH_COLLECTIONS_START,
fetchCollectionsAsync
);
}
My redux store looks like this:
import { createStore, applyMiddleware } from 'redux';
import { persistStore } from 'redux-persist';
import logger from 'redux-logger';
import createSagaMiddleware from 'redux-saga';
import {fetchCollectionsStart} from "./shop/shop.sagas";
import rootReducer from './root-reducer';
const sagaMiddleware = createSagaMiddleware();
const middlewares = [sagaMiddleware];
if (process.env.NODE_ENV === 'development') {
middlewares.push(logger);
}
export const store = createStore(rootReducer, applyMiddleware(...middlewares));
sagaMiddleware.run(fetchCollectionsStart);
export const persistor = persistStore(store);
export default { store, persistStore };
I have seen a similar question be asked at https://github.com/redux-saga/redux-saga/issues/1967.
However that answer doesn't solve it here.
Any ideas?
Thanks
As the error says, actions have to be plain objects. Apparently you are dispatching a saga instead of an action.
Replace your mapDispatchToProps code block with:
const mapDispatchToProps = (dispatch) => ({
fetchCollectionsStart: () => {
dispatch({ type: ShopActionTypes.FETCH_COLLECTIONS_START });
},
});

Invalid Chai property: matchSnapshot

I've followed instructions here: https://www.npmjs.com/package/chai-jest-snapshot
I'm using the Create-React-App starter kit and am trying to write basic Jest tests for it.
I read here that we are not suppose to install jest if we are using that kit, so here is my full package.json.
{
"name": "bitcoin",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "jest"
},
"now": {
"name": "bitcoin",
"engines": {
"node": "8.11.3"
},
"alias": "leongaban.com"
},
"dependencies": {
"axios": "^0.18.0",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-redux": "^5.0.7",
"react-scripts": "1.1.5",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"babel-plugin-transform-es2015-destructuring": "^6.23.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"chai": "^4.1.2",
"chai-jest-snapshot": "^2.0.0",
"enzyme": "^3.4.4",
"enzyme-adapter-react-16": "^1.2.0",
"react-test-renderer": "^16.4.2",
"sinon": "^6.1.5"
}
}
My Test:
import React from 'react';
import renderer from 'react-test-renderer';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import BitcoinWidget from './bitcoinWidget';
const props = {
logo: 'foo',
coin: {
price: 0
},
refresh: jest.fn()
};
// describe('<BitcoinWidget />', () => {
// it('renders three <BitcoinWidget /> components', () => {
// const wrapper = shallow(<MyComponent {...props}/>);
// expect(wrapper.find('header').length).toBe(1);
// });
// });
describe('Layout', () => {
test('renders children correctly', () => {
const wrapper = renderer
.create(
<BitcoinWidget {...props}/>
)
.toJSON();
expect(wrapper).to.matchSnapshot();
});
});
And finally the component I'm testing:
import React from 'react';
const BitcoinWidget = ({ logo, coin : { price }, refresh }) => {
return (
<div className="bitcoin-wrapper shadow">
<header>
<img src={logo} alt="Bitcoin Logo"/>
</header>
<div className="price">
Coinbase
${price}
</div>
<button className="btn striped-shadow white" onClick={refresh}>
<span>Refresh</span>
</button>
</div>
);
}
export default BitcoinWidget;
Any thoughts?
It was a problem with the packages, I didn't even need to use chai at all.
Here is my new package.json
Note the added "jest": config section:
{
"name": "bitcoin",
"version": "0.1.0",
"private": true,
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "jest src",
"test:watch": "jest src --watch"
},
"now": {
"name": "bitcoin",
"engines": {
"node": "8.11.3"
},
"alias": "leongaban.com"
},
"jest": {
"moduleNameMapper": {
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
]
},
"dependencies": {
"axios": "^0.18.0",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"react-redux": "^5.0.7",
"react-scripts": "1.1.5",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"babel-plugin-transform-es2015-destructuring": "^6.23.0",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"chai": "^4.1.2",
"chai-jest-snapshot": "^2.0.0",
"enzyme": "^3.4.4",
"enzyme-adapter-react-16": "^1.2.0",
"enzyme-to-json": "^3.3.4",
"identity-obj-proxy": "^3.0.0",
"react-test-renderer": "^16.4.2",
"sinon": "^6.1.5"
}
}
And no my test works without chai:
import React from 'react';
import renderer from 'react-test-renderer';
import Adapter from 'enzyme-adapter-react-16';
import { configure, shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
// import { expect } from 'chai';
// import sinon from 'sinon';
configure({ adapter: new Adapter() });
import BitcoinWidget from './bitcoinWidget';
let wrapper;
const props = {
logo: 'foo',
coin: {
price: 0
},
refresh: jest.fn()
};
describe('<BitcoinWidget /> layout', () => {
beforeEach(() => {
wrapper = shallow(<BitcoinWidget {...props}/>);
});
it('renders correct markup', () => {
expect(wrapper.find('header').length).toBe(1);
expect(wrapper.find('button').length).toBe(1);
});
it('should render a component matching the snapshot', () => {
const tree = toJson(wrapper);
expect(tree).toMatchSnapshot();
expect(wrapper).toHaveLength(1);
});
});

Categories

Resources