Skip to content

Commit

Permalink
Fixed @emotion/jest toHaveStyleRule on react.elements (emotion-js#1902
Browse files Browse the repository at this point in the history
)

Co-authored-by: Meno Abels <meno.abels@adviser.com>
  • Loading branch information
Andarist and mabels authored Aug 9, 2020
1 parent 4b8373b commit 472a9da
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/tiny-eels-shout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@emotion/jest': patch
---

Added support for handling regular React **elements** (objects returned from `React.createElement`) in the serializer and `toHaveStyleRule` matcher. It's possible to get those elements when traversing Enzyme's trees.
11 changes: 7 additions & 4 deletions packages/jest/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,10 @@ function getClassNamesFromDOMElement(selectors, node: any) {
}

export function isReactElement(val: any): boolean {
return val.$$typeof === Symbol.for('react.test.json')
return (
val.$$typeof === Symbol.for('react.test.json') ||
val.$$typeof === Symbol.for('react.element')
)
}

export function isEmotionCssPropElementType(val: any): boolean {
Expand Down Expand Up @@ -115,12 +118,12 @@ function isCheerioElement(val: any): boolean {

export function getClassNamesFromNodes(nodes: Array<any>) {
return nodes.reduce((selectors, node) => {
if (isReactElement(node)) {
return getClassNamesFromTestRenderer(selectors, node)
} else if (isEnzymeElement(node)) {
if (isEnzymeElement(node)) {
return getClassNamesFromEnzyme(selectors, node)
} else if (isCheerioElement(node)) {
return getClassNamesFromCheerio(selectors, node)
} else if (isReactElement(node)) {
return getClassNamesFromTestRenderer(selectors, node)
}
return getClassNamesFromDOMElement(selectors, node)
}, [])
Expand Down
14 changes: 14 additions & 0 deletions packages/jest/test/react-enzyme.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import styled from '@emotion/styled'
import React from 'react'
import toJson from 'enzyme-to-json'

import { matchers } from '@emotion/jest'
import * as serializer from '@emotion/jest/enzyme-serializer'

expect.extend(matchers)
expect.addSnapshotSerializer(serializer)

const cases = {
Expand Down Expand Up @@ -198,4 +200,16 @@ describe('enzyme', () => {

expect(toJson(wrapper, { mode: 'deep' })).toMatchSnapshot()
})

test('toHaveStyleRule on react.element', () => {
const tree = enzyme.mount(
<ul>
<li css={{ backgroundColor: 'hotpink' }}>hello</li>
</ul>
)
expect(tree.find('li').get(0)).toHaveStyleRule(
'background-color',
'hotpink'
)
})
})

0 comments on commit 472a9da

Please sign in to comment.