#javascript #reactjs #unit-testing #jestjs #react-testing-library
Вопрос:
Я всегда получаю эту ошибку всякий раз, когда пытаюсь проверить свой файл с помощью jest
и react-testing-library
ошибка —
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.
Вот мой пакет.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 amp;amp; react-scripts start",
"build": "bash ./scripts/init.sh amp;amp; react-scripts build",
"test": "bash ./scripts/init.sh amp;amp; 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"
}
}
Вот мой … babel.config.js
module.exports = {
presets: [
["@babel/preset-env", { targets: { node: "current" } }],
"@babel/preset-react",
],
};
Вот мой … 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");
});
});
Вот компонент страницы входа
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);
Я застрял в этой проблеме на несколько дней, пожалуйста, помогите
Комментарии:
1. где код модульного теста ?
2. Я добавил модульный тест, пожалуйста, посмотрите
3. Почему вы создаете
d = document.createElement
модульный тест ? Кроме того, где находится код дляLoginPage
компонента ?> Пожалуйста, убедитесь, что вы предоставили все детали, чтобы мы могли лучше помочь.4. я обновил код, пожалуйста, посмотрите