@vovashaplin

Проблема тестирования alert компонента с redux?

Тестирую Alert, который закрывается после 1 секунды. Но когда я делаю тесты, он не скрывается. Думаю проблема в функции hide, которая по каким-то причинам не скрывает alert в тестах.
Это alert.ts
import { hide } from "@/store/actions/alert";
import { getAlertInfo } from "@/store/selectors";

const Alert: React.FC = () => {
  const { text, type, isNotClose } = useSelector(getAlertInfo);
  const dispatch = useDispatch();

  useEffect(() => {
    if (isNotClose) {
      return;
    }
    setTimeout(hideHandler, 1000);
  }, [text]);

  const hideHandler = () => {
    dispatch(hide());
  };

  if (!text) return null;

  return (
    <Wrapper data-testid="alert">
      <Content type={type}>
        <Close onClick={hideHandler} />
        <Text>{text}</Text>
        <button onClick={() => hide()}>hide</button>
      </Content>
    </Wrapper>
  );
};

Это тесты, ошибку в которых выдает последняя строчка, ведь алерт не скрывается
import Alert from "./index";
import { alertReducer as reducer } from "@/store/reducers/alert";

jest.useFakeTimers();
afterEach(cleanup);

const renderWithRedux = (
  ui: React.ReactElement,
  { state, store = createStore(reducer, state) }: any = {}
) => {
  return {
    ...render(<Provider store={store}>{ui}</Provider>),
    store,
  };
};

// ...some code

  it("last test + close alert after 1000ms", async () => {
    const expectedText = "Hello, I'm Alert!";
    renderWithRedux(<Alert />, {
      state: {
        alert: {
          text: expectedText,
          typeOf: "success",
          IsNotClose: false,
        },
      },
    });

    const item = await screen.findByText(expectedText);
    expect(item).toBeInTheDocument();
    expect(screen.getByTestId("alert")).toBeInTheDocument();

    jest.advanceTimersByTime(1200);

    screen.debug();
    expect(screen.queryByTestId("alert")).not.toBeInTheDocument();
  });

Редюсер с путем @/store/reducers/alert:
import { PropertiesType } from '@/types/action';
import * as actions from './../actions/alert';

const initialState = {
    text: null as string | null,
    typeOf: 'success' as "success" | "warning" | "error",
    IsNotClose: false
};

type InititalStateType = typeof initialState;

type AlertActionsTypes = ReturnType<PropertiesType<typeof actions>>

export const alertReducer = (state = initialState, action: AlertActionsTypes): InititalStateType => {
    switch (action.type) {
        case 'ALERT_SHOW':
            return { ...state, text: action.text, typeOf: action.typeOf, IsNotClose: action?.IsNotClose ? true : false }
        case 'ALERT_HIDE':
            return { ...state, text: null }
        default:
            return state;
    }
}

Экшены с путем @/store/actions/alert
export type typeOfType = 'success' | 'warning' | 'error'
export const hide = () => ({ type: 'ALERT_HIDE' } as const);
export const show = (text: string, typeOf: typeOfType = 'success', IsNotClose?: boolean) => ({ type: 'ALERT_SHOW', text, typeOf, IsNotClose } as const);
  • Вопрос задан
  • 30 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
28 мар. 2024, в 20:09
1500 руб./в час
28 мар. 2024, в 19:53
100000 руб./за проект
28 мар. 2024, в 19:34
10000 руб./за проект