#reactjs #authentication #jestjs #passport.js #react-testing-library
#reactjs #аутентификация #jestjs #passport.js #реагировать-тестирование-библиотека
Вопрос:
Я пытаюсь протестировать процесс моего кода, когда пользователь вводит правильную информацию; однако я застрял на ошибке, в которой указано, что authContext рассматривается как неопределенный. Правильно ли я это тестирую? Как мне исправить эту ошибку?
ошибка
TypeError: Cannot read property 'setUser' of undefined
25 | const { isAuthenticated, user } = data;
26 | if (isAuthenticated) {
> 27 | authContext.setUser(user);
loginForm.test.js
test('user input correct login information', () => {
const { getByTestId, getByText } = render(<LoginForm />);
const resInfo = {username: 'Bpun1p'}
const resp = {isAuthenticated: true, user: resInfo}
AuthService.login.mockResolvedValue(resp)
fireEvent.change(getByTestId('Username'), {target: {value: "Bpun1p"}})
fireEvent.change(getByTestId('Password'), {target: {value: "Guy123su"}})
fireEvent.click(getByTestId('LoginBtn'));
});
loginForm.js
import React, { useContext, useState } from 'react';
import { useHistory } from 'react-router-dom';
import SocialSignUp from './SocialSignUp';
import { AuthContext } from '../../context/AuthContext';
import AuthService from '../../service/AuthService';
function LoginForm() {
const [username, setUsername] = useState({ username: '' });
const [isValidEntry, setValidEntry] = useState(true);
const authContext = useContext(AuthContext);
const history = useHistory();
const onChange = (event) => {
setUsername({ ...username, [event.target.name]: event.target.value });
};
const onSubmit = (event) => {
event.preventDefault();
if (username.username !== '') {
AuthService.login(username)
.then((data) => {
console.log(data);
const { isAuthenticated, user } = data;
if (isAuthenticated) {
authContext.setUser(user);
authContext.setIsAuthenticated(isAuthenticated);
history.push('/profile/global');
} else setValidEntry(false);
});
} else setValidEntry(false);
};
Ответ №1:
в тесте <LoginForm/>
замените на <AuthContext.Provider> <LoginForm/><AuthContext.Provider>
и передайте необходимые реквизиты для AuthContext.Поставщик для запуска приложения