Невозможно выполнить модульный тест в стиле компонента, который переопределяет материал-интерфейс - PullRequest
0 голосов
/ 02 мая 2018

У меня есть стилизованный компонент для элемента навигационного списка, который оборачивает элемент списка Material-UI и использует '&&' для переопределения стилей без использования флагов! Important.

import { ListItem } from 'material-ui/List'

export const StyledNavListItem = withTheme()(styled(ListItem)`
  && {
    background: ${props => props.selected
    ? props.theme.palette.backgrounds.selected
    : 'inherit'};
  }
`)

Это реализовано так:

export const NavListItem = props => {
  return (
    <StyledNavListItem selected={props.selected} component={Link} to={props.to || ''} onClick={props.onClick || (() => false)} button>
      {props.icon && <ListItemIcon><Icon name={props.icon} /></ListItemIcon>}
      <ListItemText primary={props.children || ''} />
    </StyledNavListItem>
  )
}

Но, при попытке выполнить здесь юнит-тест (с Jest, энзимом и jest-styled-компонентами):

it('should change the background color of an item if `props.selected` is truthy', () => {
    const navList = mount(
      <MuiThemeProvider theme={theme}>
        <BrowserRouter>
          <Route>
            <NavList>
              <NavListItem>item text</NavListItem>
              <NavListItem selected>item text</NavListItem>
            </NavList>
          </Route>
        </BrowserRouter>
      </MuiThemeProvider>
    )
    expect(navList.find(StyledNavListItem).at(0)).toHaveStyleRule('background', '#e0e0e0')
    expect(navList.find(StyledNavListItem).at(1)).toHaveStyleRule('background', theme.palette.backgrounds.selected)
  })

Я получаю сообщение об ошибке Property not found: "background" Если я удалю обертку '&&' из моих стилей, тесты пройдут без проблем, но тогда я не получу стили для работы с компонентом. Есть ли способ добраться до этого блока переопределения, чтобы проверить его?

1 Ответ

0 голосов
/ 04 мая 2018

Я нашел решение - указав пользовательские классы в компоненте material-ui, а затем сославшись на него в стилях, он прекрасно работает с прикрепленным модификатором

Пример Typography.style.js

import React from 'react'
import { withTheme } from 'material-ui/styles'
import styled, { css } from 'styled-components'
import Typography from 'material-ui/Typography'

export const StyledTypography = withTheme()(styled(({emphasized, strong, inlined, color, ...other}) => {
  return <Typography {...other} classes={{root: 'typography-root'}} />
})`
  &.typography-root {
    line-height: 1.2em;
    ${props => !props.variant && css`
      font-size: 1em;
    `}
    ${props => props.color && props.theme.palette.typography[props.color] && css`
      color: ${props.theme.palette.typography[props.color]};
    `}
    ${props => props.strong && css`
      font-weight: 500;
    `}
    ${props => props.emphasized && css`
      font-style: italic;
    `}
    ${props => props.inlined && css`
      display: inline-block;
    `}
  }
`)

Test

it('does something', () => {
    const typography = mount(
      <MuiThemeProvider theme={praxisTheme}>
        <Typography />
      </MuiThemeProvider>
    )
    expect(typography.find(MaterialUITypography)).toHaveStyleRule('line-height', '1.2em', { modifier: '&.typography-root' })
  })
...