Skip to content

Instantly share code, notes, and snippets.

@treshugart
Created February 3, 2017 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treshugart/d0ddc64f22172f5f68e6b7b8ab471306 to your computer and use it in GitHub Desktop.
Save treshugart/d0ddc64f22172f5f68e6b7b8ab471306 to your computer and use it in GitHub Desktop.
I used https://github.com/lelandrichardson/enzyme-example-karma-webpack for a default setup and then put the following in the test file.
import React, { Component } from 'react';
import styled from 'styled-components';
import { mount } from 'enzyme';
describe("A suite", function() {
it("should select an element using standard and non-standard DOM attributes", function() {
const StyledComponent = styled.div`
background-color: black;
`;
class Test extends Component {
render () {
return (
<div>
<StyledComponent value="test" />
<StyledComponent value="test" nonStandard="test" />
</div>
);
}
}
expect(mount(<Test />).find({
value: 'test'
}).length).toBe(2, 'standard');
expect(mount(<Test />).find({
nonStandard: 'test'
}).length).toBe(1, 'non-standard');
expect(mount(<Test />).find({
nonStandard: 'test',
value: 'test'
}).length).toBe(1, 'mixture');
});
});
@treshugart
Copy link
Author

treshugart commented Feb 3, 2017

The problem here is that the 2nd and 3rd assertions fail and return 0 results when there should be 1 in both. The first is correct because it contains value, a standard attribute, but the others contain nonStandard.

I haven't created an issue because I'm unsure if this is an issue with Styled Components or Enzyme. I know Styled Components pass through props but it seems that Enzyme can't select based on attributes that aren't in React's attribute inclusion list. In this case, that's nonStandard, whereas value works because that is valid on something like <input />.

@mxstbr
Copy link

mxstbr commented Feb 3, 2017

The issue here is that you're trying to attach non standard HTML attributes, which is discouraged from React. Instead, use a data-x attribute, which will correctly be passed through by styled-components, e.g. data-non-standard="test" will work perfectly fine.

@treshugart
Copy link
Author

The purpose of these is to use them in the tagged literal as props, so need non string values to work. Don't have the capacity to try at the moment if that will yield expected results but will have a go on Monday. Thanks again for your response, @mxstbr!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment