Skip to content

Commit

Permalink
feat(toHaveStyleRule): add support for component modifiers
Browse files Browse the repository at this point in the history
Augments the modifier syntax to allow nested component rules such as
```
const Child = styled.div`
  color: blue;
`;

const Parent = styled.div`
  display: flex;

  ${Child} {
    flex: 1;
  }
`;

fixes #64
  • Loading branch information
Joel Kang committed Feb 11, 2018
1 parent 4afa974 commit 7a9dae7
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/toHaveStyleRule.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const { getCSS } = require('./utils')
const { isStyledComponent } = require('styled-components')

const shouldDive = node =>
typeof node.dive === 'function' && typeof node.type() !== 'string'
Expand Down Expand Up @@ -87,9 +88,20 @@ const getDeclaration = (rule, property) =>
const getDeclarations = (rules, property) =>
rules.map(rule => getDeclaration(rule, property)).filter(Boolean)

const normalizeModifierOption = (modifiers = []) =>
modifiers
.map(
modifier =>
isStyledComponent(modifier)
? `.${modifier.styledComponentId}`
: modifier
)
.join('')

function toHaveStyleRule(received, property, value, options = {}) {
const classNames = getClassNames(received)
const ast = getCSS()
options.modifier = normalizeModifierOption([].concat(options.modifier))
const rules = getRules(ast, classNames, options)

if (!rules.length) {
Expand Down
55 changes: 55 additions & 0 deletions test/toHaveStyleRule.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -257,3 +257,58 @@ test('selector modifiers', () => {
modifier: '.parent &',
})
})

test('component modifiers', () => {
const Text = styled.span`
color: grey;
`

const Link = styled.a`
color: white;
${Text} {
color: blue;
}
> ${Text} span {
color: green;
}
${Text} & {
color: purple;
}
`

toHaveStyleRule(<Link />, 'color', 'white')
toHaveStyleRule(<Text />, 'color', 'grey')
toHaveStyleRule(
<Link>
<Text />
</Link>,
'color',
'blue',
{
modifier: Text,
}
)
toHaveStyleRule(
<Link>
<Text />
</Link>,
'color',
'green',
{
modifier: ['> ', Text, ' span'],
}
)
toHaveStyleRule(
<Link>
<Text />
</Link>,
'color',
'purple',
{
modifier: [Text, ' &'],
}
)
})

0 comments on commit 7a9dae7

Please sign in to comment.