-
-
Notifications
You must be signed in to change notification settings - Fork 145
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
v7.0.0 No Styles found on passed Component #294
Comments
The potential merge is being blocked by styled-components/jest-styled-components#294
I'm not very familiar with the inner workings of SC or this package, but I think I may have tracked the issue down to here: 8c2ea4a#diff-4eed74593d3d8efde6a0959c9c35119bR71 In my case the static classes have names of the format "Component-sc-hashstuff", but the filter expects them to start with 'sc-', so none are found. Then due to the way the some() calls are nested, hasClassNames returns false when I don't think it should. |
My issue with this boiled down to 'babel-plugin-styled-components' being used. That plugin modifies the class names to include the component, removing that fixed the issue. See #290 |
We need the |
I'm having the same problem with enzyme. |
I'm seeing the same issue even with displayName set to
Test:
Tree:
Message:
|
I'm having this same issue styled 4.4.1, and 6.3.4 of this lib, not sure. For now I'm rolling with a local patch-package that seems to fix things. Hoping the update to 7 here and styled 5 fixes. I'll following this repo and lmk if I can help in any way. :D |
We are having the same issue with styled-components 5.0.0 and jest-styled-components 7. To fix it we are currently using:
|
This is a duplicate of #290 |
Having a similar issue when using: "jest": "^25.1.0",
"jest-styled-components": "^7.0.0",
"@testing-library/jest-dom": "^4.0.0",
"@testing-library/react": "^9.1.1",
"babel-plugin-styled-components": "^1.10.7",
"styled-components": "^5.0.1", And configuring babelrc:
Test is: it('should be visible', () => {
const { getByTestId } = render(
...
);
const cta = getByTestId('cta-id');
fireEvent.click(cta);
expect(getByTestId('content')).toMatchSnapshot();
expect(getByTestId('content')).toHaveStyleRule('visibility', 'visible');
}); The snapshot clearly shows that styles are there:
But assertion says: |
This is still broken for me, even with:
|
This is also preventing us from upgrading to v7. |
I saw that 7.0.2 was released, I'm still having trouble getting it to work with Styled components v5.1.0 and react-testing-library. I think it does have something to do with the class name used and the regex code in jest-styled-components to parse it. It looks like the regex is looking for "sc-" but my component is outputting a different pattern. Here's the test:
here is a debug() output of the component:
When I output the snapshot I see the style rule does exist.
Test output shows:
Dependencies:
|
@fullstackzach having the same issue here |
Adding to this: I'm seeing the same issue on the
|
* Upgrade fix and feature in storybook * Remove core-js as dependency as it doesn't seems to be used directly, but rather by other packages * Use @storybook/source-loader instead of @storybook/addon-storysource/loader because of deprecation warning * ⬆️ Upgrade styled-components from 4 to 5.1.1 * Upgrade fix and feat. Upgrade github-markdown-css to 4.0.0 * ⬆️ Upgrade Prettier from 1.19.1 to 2.0.5. We already use the new defaults for trailingComma, arrowParens and endOfLine * ⬆️ Upgrade react-helmet from 5.x.x to 6.0.0. Missing title almost everywhere, but that's not caused by this upgrade * ⬆️ Upgrade gatsby-plugin-matomo from 0.7.2 to 0.8.3 * ⬆️ Upgrade fix and feature * ⬆️ Upgrade prettier from 1.19.1 to 2.0.5 * :arrow_up; Upgrade ramda from 0.26.1 to 0.27.0. No upgrade guide, so assuming it's safe even if there is no real semver * ⬆️ Upgrade fix and feature. Upgrade prettier from 1.19.1 to 2.0.5 * Replace deprecated rollup-plugin-babel with @rollup/plugin-babel * Replace deprecated rollup-plugin-json with @rollup/plugin-json * ⬆️ Upgrade rollup from 1.32.1 to 2.15.0 * Replace rollup-plugin-node-resolve and rollup-plugin-commonjs with corresponding @rollup/plugin-x * ⬆️ Upgrade ætesting-library/jest-dom from 4.2.4 to 5.9.0 * Update test to work * Downgrade styled-components og jest-styled-components because of a bug https://github.com/styled-components/jest-styled-components/issues/294\#issuecomment-613084524 * Upgrade prettier. Fix eslint errors. Support for optional chaining with eslint * ⬆️ Upgrade fix and features * Remove eslint-config-airbnb, use eslint:recommended as defaults instead * Upgrade eslint from 6.8.0 to 7.2.0. Remove duplicate eslint settings in core to avoid errors * Add some more eslint rules * Add missing semi * Add missing semi * Merge * Add missing displayName * Add node engine greater than 10 * Add hard space back in * ⬆️ Upgrade rollup and @rollup/plugin-node-resolve * ⬆️ Upgrade rollup and @rollup/plugin-node-resolve
Probably similar?
import styled from "styled-components";
import React from "react";
import {mount} from "enzyme";
import 'jest-styled-components';
const Foo = () => (
<div>Bar</div>
);
const StyledFoo = styled(Foo)`
color: mediumspringgreen;
`;
describe('StyledFoo', () => {
it('has a mediumspringgreen color', () => {
const styledFoo = mount(<StyledFoo />);
expect(styledFoo).toHaveStyleRule('color', 'mediumspringgreen');
});
}); Snapshot:
But I get However, if I introduce const Foo = ({className}: {className?: string}) => (
<div className={className}>Bar</div>
); Snapshot:
Is this expected? |
So... I had similar issue and I have already pointed out the problem in this comment In short the algorithm is built so that you HAVE TO have the I have already proposed to fix it, but as I am not sure how the procedure work I won't start any correction before I get a green light to do so. |
I got it working for me with the new module.exports = {
// ...
env: {
test: {
plugins: [
[
'babel-plugin-styled-components',
{ ssr: false, displayName: false, namespace: 'sc' },
],
],
},
},
}; |
Simply adding the package react-test-renderer as a dependency fixed this issue for me:
Also, here's my babel config: {
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true }]]
} |
@oguzgelal , react-test-renderer installed, but problem still exists. jest-styled-components checking is hardcoded.
styles should masker with "sc-". Snapshot from another my project with working: <div
class="indextest__DivStyled-sc-1wt13as-0 hViIRb"
>
Text
</div> "sc-" in classname exists. But on broken project not exists: <div
class="indextest__DivStyled-p00oe-0 jAwXaO"
>
Text
</div> To fix i have to add namespace to babel config.
|
i got the same problem. i saw that there where multiple versions of styled components included (v5.1 and v5.2). removing v5.2 did the trick for me |
This worked for me! Using nx.dev |
Using Jest |
Maybe another slight piece to someone's puzzle. I've had to solve this a half dozen times and this is yet another scenario for me. Both specificity and the ❌ Broken import styled from 'styled-components';
import { mount } from 'enzyme';
const Checkbox = styled.input`
input[type='checkbox']& {
height: 20px;
}
`;
test('fails', () => {
expect(mount(<Checkbox />)).toHaveStyleRule('height', '20px');
});
test('fails w/ modifier', () => {
expect(mount(<Checkbox />)).toHaveStyleRule('height', '20px', {
modifier: "input[type='checkbox']", // no combination of this worked here like it does in other tests…
});
}); 🎉 I got it passing by changing the component itself, adding import styled from 'styled-components';
import { mount } from 'enzyme';
const Checkbox = styled.input`
&,
input[type='checkbox']& {
height: 20px;
}
`;
test('passes', () => {
expect(mount(<Checkbox />)).toHaveStyleRule('height', '20px');
}); I hope no one's really using this specific pattern scenario, but it might highlight specificity issues to people debugging. |
Previously ```js expect(Element).toHaveStyleRule('some', 'args') ``` had problems rendering, similar to problems mentioned here: styled-components/jest-styled-components#294 the prefix of sc in babel-styled-components did not work. I tried to debug the jest-styled-components matcher, but alas.
I'm receiving an error Setup:
|
try with our babel config: const defaultConfig = {
presets: ["next/babel"],
plugins: [],
};
module.exports = ({ env }) => {
if (env("test")) {
return {
...defaultConfig,
plugins: [
...defaultConfig.plugins,
[
"babel-plugin-styled-components",
{ ssr: false, displayName: false, namespace: "sc" },
],
],
};
}
return {
...defaultConfig,
plugins: [
...defaultConfig.plugins,
["babel-plugin-styled-components", { ssr: true, namespace: "sc" }],
],
};
}; |
Just a heads-up: none of the above seems to work for me, either with enzyme's By "none of the above" I mean any Versions: "jest-styled-components": "7.0.5",
"styled-components": "5.3.3"
"react-test-renderer": "17.0.2"
"enzyme": "3.11.0",
"babel-plugin-styled-components": "1.13.3", My current workaround (this gist):
import renderer, { ReactTestRendererJSON } from 'react-test-renderer'
export function render(component: React.ReactElement) {
return (
renderer
.create(component)
.toJSON() as ReactTestRendererJSON
)
}
export function renderClasses(component: React.ReactElement): string[] {
const {
props: { className },
} = render(component)
return className ? className.trim().split(' ') : []
}
type ComputedStyles = Record<string, string | Record<string, string>>
export function getComputedStyles(className: string) {
const div = document.createElement('div')
div.className = className
const computed: ComputedStyles = {}
for (const sheet of document.styleSheets) {
for (const rule of sheet.cssRules) {
if (rule instanceof CSSMediaRule) readMedia(rule)
else if (rule instanceof CSSStyleRule) readRule(rule, computed)
}
}
return computed
function matchesSafe(node: HTMLDivElement, selector: string) {
if (!selector) return false
try {
return node.matches(selector)
} catch (error) {
return false
}
}
function readRule(rule: CSSStyleRule, dest: ComputedStyles) {
if (matchesSafe(div, rule.selectorText)) {
const { style } = rule
for (let i = 0; i < style.length; i++) {
const prop = style[i]
dest[prop] = style.getPropertyValue(prop)
}
}
}
function readMedia(mediaRule: CSSMediaRule) {
const key = `@media ${mediaRule.media[0]}`
const dest = {}
for (const rule of mediaRule.cssRules) {
if (rule instanceof CSSStyleRule) readRule(rule, dest)
}
if (Object.keys(dest).length > 0) computed[key] = dest
}
}
/* Return styles from all classes applied merged into a single object. */
export function getStyles(comp: React.ReactElement) {
return renderClasses(comp)
.filter(c => !c.includes('sc'))
.map(getComputedStyles)
.reduce((result, current) => Object.assign(result, current), {})
} Then we can use the import { getStyles } from './test-helpers'
test('extended components keep their styles', () => {
const Box = styled.div`
margin: 16px;
`
const Card = styled(Box)`
color: tomato;
`
const styles = getStyles(<Card />)
expect(styles).toEqual({ margin: '16px', color: 'tomato' })
}) |
This worked for me 🥳 Thanks! |
None of the recommended solutions are working for me so far |
Adding the line below in babel.config.js fixed it for me: // our project originally had ssr as false , process.env.NODE_ENV === 'test' sets it as true when running tests. when using: "react-test-renderer": "^17.0.2" |
Seems to happen to me when switching from commonjs to esnext for me. None of the solutions worked above. Been to pretty much every GitHub/Stackoverflow thread related to this and nothing worked. I'm guessing something is breaking due to the switch? No clue what package or how to fix it though I'm using
Reverting to the versions below fixes it even without reverting back to commonjs. This is super frustrating :(
Code example
|
To me none of the above fixes worked and I found why it was working for me in some test files but not in others: I was creating the renderer INSIDE the DESCRIBE and it was like 'jest-styled-components' was not being applied to those test files. I moved the renderer creation to every single test (test/it) and worked:
"styled-components": "^5.3.6", |
I've just updated styled components to v5 and jest-styled-components to v7 and now any test that calls on
toHaveStyleRule
fails with the errorNo style rules found on passed Component
.Example test
Tested component
This test passed using styled components v4.3.2 and jest-styled-components v6.3.3.
This is being tested with @testing-library/react v9.1.4
The text was updated successfully, but these errors were encountered: