Skip to content
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

Enhance toHaveStyle to accept JS as css #196

Merged
merged 2 commits into from Jan 31, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/__tests__/to-have-style.js
@@ -1,6 +1,7 @@
import {render} from './helpers/test-utils'
import document from './helpers/document'

// eslint-disable-next-line max-lines-per-function
gnapse marked this conversation as resolved.
Show resolved Hide resolved
describe('.toHaveStyle', () => {
test('handles positive test cases', () => {
const {container} = render(`
Expand Down Expand Up @@ -144,4 +145,25 @@ describe('.toHaveStyle', () => {
'whatever: anything',
)
})

test('handles styles as object', () => {
const {container} = render(`
<div class="label" style="background-color: blue; height: 100%">
Hello World
</div>
`)

expect(container.querySelector('.label')).toHaveStyle({
backgroundColor: 'blue',
})
expect(container.querySelector('.label')).toHaveStyle({
backgroundColor: 'blue',
height: '100%',
})
expect(container.querySelector('.label')).not.toHaveStyle({
backgroundColor: 'red',
height: '100%',
})
// expect(container.querySelector('.label')).not.toHaveStyle({ whatever: 'anything' })
})
})
13 changes: 12 additions & 1 deletion src/to-have-style.js
Expand Up @@ -48,8 +48,19 @@ function expectedDiff(expected, computedStyles) {
return diffOutput.replace(`${chalk.red('+ Received')}\n`, '')
}

export function toHaveStyle(htmlElement, css) {
function getCss(document, css) {
if (typeof css === 'object') {
const sandboxElement = document.createElement('div')
Object.assign(sandboxElement.style, css)
return sandboxElement.style.cssText
}
gnapse marked this conversation as resolved.
Show resolved Hide resolved

return css
}

export function toHaveStyle(htmlElement, expectedCss) {
checkHtmlElement(htmlElement, toHaveStyle, this)
const css = getCss(htmlElement.ownerDocument, expectedCss)
const parsedCSS = parseCSS(css, toHaveStyle, this)
const {getComputedStyle} = htmlElement.ownerDocument.defaultView

Expand Down