From 7a9dae7c73ddf6f45c5222fc1742f3de84864f8e Mon Sep 17 00:00:00 2001 From: Joel Kang Date: Sat, 10 Feb 2018 22:30:54 -0500 Subject: [PATCH] feat(toHaveStyleRule): add support for component modifiers 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 --- src/toHaveStyleRule.js | 12 ++++++++ test/toHaveStyleRule.spec.js | 55 ++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/src/toHaveStyleRule.js b/src/toHaveStyleRule.js index 63c43e4..ea705d5 100644 --- a/src/toHaveStyleRule.js +++ b/src/toHaveStyleRule.js @@ -1,4 +1,5 @@ const { getCSS } = require('./utils') +const { isStyledComponent } = require('styled-components') const shouldDive = node => typeof node.dive === 'function' && typeof node.type() !== 'string' @@ -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) { diff --git a/test/toHaveStyleRule.spec.js b/test/toHaveStyleRule.spec.js index bc0965c..b81b5ac 100644 --- a/test/toHaveStyleRule.spec.js +++ b/test/toHaveStyleRule.spec.js @@ -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(, 'color', 'white') + toHaveStyleRule(, 'color', 'grey') + toHaveStyleRule( + + + , + 'color', + 'blue', + { + modifier: Text, + } + ) + toHaveStyleRule( + + + , + 'color', + 'green', + { + modifier: ['> ', Text, ' span'], + } + ) + toHaveStyleRule( + + + , + 'color', + 'purple', + { + modifier: [Text, ' &'], + } + ) +})