Запустить Mock Service Worker и проверить где ошибка?

Добрый день!
Может кто уже сталкивался с такой проблемой, а может я что-то не так делаю?
У меня есть компонент - он работает проблем нет
import React, { FC } from 'react';
import useSWR from 'swr';
import Bell from '@/svg/bell.svg';
import Cross from '@/svg/cross.svg';
import styles from './AlertTopLine.module.css';

export const AlertTopLine: FC = (): JSX.Element | null => {
  const { data, error, isLoading } = useSWR('/data/alert.json');
  if (sessionStorage.getItem('alert') === 'false') return null;

  const hiddenAlertSection = () => {
    sessionStorage.setItem('alert', 'false');
    let alert = document.getElementById('alert');
    alert ? alert.classList.add(styles.hidden) : null;
  };
  return !isLoading && !error && data?.active ? (
    <div
      className={styles.section}
      id='alert'
      style={{ '--color-alert': `var(--color-${data?.type || 'info'})` } as React.CSSProperties}
    >
      <div className={styles.wrapper}>
        <div className={styles.icoCircle}>
          <Bell className={styles.icoBell} />
        </div>
        <div className={styles.text}>
          {data.text && data.text}
          {data.text && data.link && (
            <a
              onClick={() => {
                hiddenAlertSection();
              }}
              href={data.link}
            >
              Перейти
            </a>
          )}
        </div>
        <div
          style={{ zIndex: '100' }}
          onClick={() => {
            hiddenAlertSection();
          }}
          title='Закрыть'
        >
          <Cross className={styles.icoCross} />
        </div>
        <div className={styles.circleOne}></div>
        <div className={styles.circleTwo}></div>
      </div>
    </div>
  ) : null;
};


К нему пишу тест, для этого использую "Mock Service Worker "
Нашел примеры, сделал все как в примерах, но получается что ничего не приходит от mock сервера
То-есть просто useSWR - ничего не получает
Вот код теста:
import { render, screen } from '@testing-library/react';
import { AlertTopLine } from './index';
import { setupServer } from 'msw/node';
import { rest } from 'msw';
import { SWRConfig } from 'swr';
import 'whatwg-fetch'; // ?????

const server = setupServer(
  rest.get('/data/alert.json', (req, res, ctx) => {
    return res(
      // ctx.delay(100),
      ctx.status(200),
      ctx.json({
        active: true,
        type: 'danger',
        text: 'Правила приёма отдыхающих в санаторий Подробнее можно прочесть здесь',
        link: '#',
      }),
    );
  }),
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

describe('Работа виджета', () => {
  it('renders', async () => {
    await render(
      <SWRConfig
        value={{
          dedupingInterval: 0,
          provider: () => new Map(),
          fetcher: (resource, init) => fetch(resource, init).then((res) => res.json()),
        }}
      >
        <AlertTopLine />
      </SWRConfig>,
    );
    await screen.debug();

    // expect(screen.getByText('Перейти')).toMatchSnapshot();
    // expect(screen.getByText('Правила')).toBeInTheDocument();
  });
});


screen.debug() поазывает:

console.log
    <body>
      <div />
    </body>
  • Вопрос задан
  • 44 просмотра
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы