Как проверить эту строку в React with Jest? - PullRequest
0 голосов
/ 11 января 2020

Я пытаюсь достичь 100% тестового покрытия, и есть одна строка, которую я просто не знаю, как тестировать. Может кто-нибудь мне помочь? Я использую Jest, React-testing-library и, конечно, ReactJS.

Буду также признателен за объяснение того, как тестировалась линия, поскольку я пытаюсь стать лучше в тестировании.

const LatestDataListItem = props => {
  const getThemeTone = useThemeTone(); /* this hooks is simply returning a string(whick can be dark or light) */
  return (
      <StyledItem {...props}>
        <StyledValue
          primaryTextProps={{
            style: {
              fontSize: '32px',
              color: isCaution(props) /* this is what i'm trying to cover */ 
                ? getCautionColorByTheme(getThemeTone).red
                : getCautionColorByTheme(getThemeTone).blue
            }
          }}
        />
      </StyledItem>
  );
};

Строка комментария - это то, что я пытаюсь проверить:

color: isCaution(props) 
? getCautionColorByTheme(getThemeTone).red : getCautionColorByTheme(getThemeTone).blue

Это функция isCaution:

const isCaution = ({ caution }) => {
  return true; /* returning true only to make easier to post here */
};

И это getCautionColorByTheme:

const colorsByThemeTone = {
  light: {
    blue: '#0d3459',
    red: '#f2463d',
    lightRed: 'rgba(255, 0, 0, 0.07)'
  },
  dark: {
    blue: '#e8e8e8',
    red: '#fa5a4b',
    lightRed: '#fa5a4b'
  }
};

const getCautionColorByTheme = themeTone => {
  return colorsByThemeTone[themeTone];
};

Так что получается, что colorsByThemeTone - это объект двух типов: светлый и темный. getThemeTone возвращает, если тема темная или светлая, и вот как я получаю цвета.

Я думал, что, возможно, мне нужно экспортировать getCautionColorByTheme для импорта в мой файл .test.js и проверить эту функцию внутри, но Я не знаю, как именно это сделать.

Вот что я попробовал:

  it('should render the test getCautionColorByTheme receiving light theme', () => {
    const colorsByThemeTone = {
      light: {
        blue: '#0d3459',
        red: '#f2463d',
        lightRed: 'rgba(255, 0, 0, 0.07)'
      },
      dark: {
        blue: '#e8e8e8',
        red: '#fa5a4b',
        lightRed: '#fa5a4b'
      }
    };
    const result = getCautionColorByTheme('light');
    expect(result).toMatchObject(colorsByThemeTone.light);
  });

Спасибо!

1 Ответ

0 голосов
/ 11 января 2020

Я предлагаю сделать getCautionColorByTheme() чистой функцией:

const getCautionColorByTheme = (themeTone) => {
  const colorsByThemeTone = {
    light: {
      blue: '#0d3459',
      red: '#f2463d',
      lightRed: 'rgba(255, 0, 0, 0.07)'
    },
    dark: {
      blue: '#e8e8e8',
      red: '#fa5a4b',
      lightRed: '#fa5a4b'
    }
  };

  return colorsByThemeTone[themeTone];
}

или для более гибкой реализации (необходимо настроить потребителей на getCautionColorByTheme()):

const getCautionColorByTheme = ({
  themeTone,
  colorsByThemeTone = {
    light: {
    blue: '#0d3459',
    red: '#f2463d',
    lightRed: 'rgba(255, 0, 0, 0.07)'
  },
  dark: {
    blue: '#e8e8e8',
    red: '#fa5a4b',
    lightRed: '#fa5a4b'
  }
 }
}) => colorsByThemeTone[themeTone]

А если еще нет, сделайте isCaution() чистым тоже. Таким образом, вы можете протестировать логи c изолированно.

it('should render the test getCautionColorByTheme receiving light theme', () => {
  // should be the same what's the value in getCautionColorByTheme()
  // better if the default value in `getCautionColorByTheme()` is
  // exported as a variable and then used in the test.
  const colorsByThemeTone = {
    light: {
      blue: '#0d3459',
      red: '#f2463d',
      lightRed: 'rgba(255, 0, 0, 0.07)'
    },
    dark: {
      blue: '#e8e8e8',
      red: '#fa5a4b',
      lightRed: '#fa5a4b'
    }
  };

  const result = getCautionColorByTheme('light');

  expect(result).toMatchObject(colorsByThemeTone.light);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...