Skip to content

Commit

Permalink
Add support for nested media querie assertions
Browse files Browse the repository at this point in the history
  • Loading branch information
ankeetmaini committed Apr 25, 2020
1 parent 420f161 commit b055195
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 14 deletions.
19 changes: 19 additions & 0 deletions packages/jest/src/__tests__/matchers.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,4 +165,23 @@ describe('toHaveCompliedCss', () => {
const el = getByText('hello world');
expect(el).toHaveCompiledCss('background', 'red', { media: 'screen', target: ':hover' });
});

it('should match styles with media nested inside class', () => {
const { getByText } = render(
<div
css={{
'@media (min-width: 2px)': {
color: 'blue',
'@media (min-width: 1px)': {
color: 'red',
},
},
}}>
hello world
</div>
);
const el = getByText('hello world');
expect(el).toHaveCompiledCss('color', 'blue', { media: '(min-width: 2px)' });
expect(el).toHaveCompiledCss('color', 'red', { media: '(min-width: 1px)' });
});
});
32 changes: 18 additions & 14 deletions packages/jest/src/matchers.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import CSS from 'css';
import CSS, { StyleRules, Media } from 'css';
import { MatchFilter } from './types';

type Arg = [{ [key: string]: string }, MatchFilter?];
Expand All @@ -22,6 +22,22 @@ const getMountedProperties = () =>
)
.join(' ');

const onlyRules = (rules?: StyleRules['rules']) => rules?.filter(r => r.type === 'rule');

const findMediaRules = (
allRules: StyleRules['rules'] = [],
media: string
): Media['rules'] | undefined => {
for (const rule of allRules) {
if (!rule) return;
if ('media' in rule) {
if (rule.media === media.replace(/\s/g, '') && 'rules' in rule) return rule.rules;
if ('rules' in rule) return findMediaRules(rule.rules, media);
}
}
return;
};

const getRules = (ast: CSS.Stylesheet, filter: MatchFilter, className: string) => {
const { media, target } = filter;

Expand All @@ -30,19 +46,7 @@ const getRules = (ast: CSS.Stylesheet, filter: MatchFilter, className: string) =
// this inner function returns the relevant rules
const getAllRules = () => {
if (media) {
const mediaRules = ast.stylesheet?.rules.filter(r => {
if ('media' in r) {
return r.media === media;
}
return;
});

return mediaRules?.reduce<CSS.Rule[]>((acc, m) => {
if ('rules' in m && m.rules) {
acc = [...acc, ...m.rules];
}
return acc;
}, []);
return onlyRules(findMediaRules(ast.stylesheet?.rules, media));
}
return ast.stylesheet?.rules.filter(r => (r.type = 'rule')); // omit media objects
};
Expand Down

0 comments on commit b055195

Please sign in to comment.