Skip to content

Commit

Permalink
Fix: Validate style attributes on the RHS
Browse files Browse the repository at this point in the history
We currently ignore empty styles in RHS which is quite surprising. This commit
fixes it by validating the RHS styles.
  • Loading branch information
sunesimonsen committed Oct 24, 2018
1 parent f4a218f commit 1d568a7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,20 @@ function isEnumeratedAttribute(attrName) {
return attrName in enumeratedAttributeValues;
}

function validateStyles(expect, str) {
var invalidStyles = str.split(';').filter(function(part) {
return !/^\s*\w+\s*:\s*\w+\s*$|^$/.test(part);
});

if (invalidStyles.length > 0) {
expect.errorMode = 'nested';
expect.fail(
'Expectation contains invalid styles: {0}',
invalidStyles.join(';')
);
}
}

function styleStringToObject(str) {
var styles = {};

Expand Down Expand Up @@ -1126,6 +1140,7 @@ module.exports = {
} else if (attributeName === 'style') {
var expectedStyleObj;
if (typeof expectedValueByAttributeName.style === 'string') {
validateStyles(expect, expectedValueByAttributeName.style);
expectedStyleObj = styleStringToObject(
expectedValueByAttributeName.style
);
Expand Down
28 changes: 28 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1849,6 +1849,34 @@ describe('unexpected-dom', function() {
);
});

it('should not fail for invalid style attributes on the LHS', function() {
return expect(
parseHtml('<div style="color; width: 120px;">hey</div>'),
'to satisfy',
parseHtml('<div style="width: 120px;">hey</div>')
);
});

it('should fail when the RHS has invalid styles', function() {
return expect(
function() {
return expect(
parseHtml('<div style="width: 120px;">hey</div>'),
'to satisfy',
parseHtml('<div style="color;background;width: 120px">hey</div>')
);
},
'to error',
'expected <div style="width: 120px">hey</div> to satisfy <div style="width: 120px">hey</div>\n' +
'\n' +
'<div\n' +
' style="width: 120px" // expected <div style="width: 120px">hey</div>\n' +
" // to satisfy { name: 'div', attributes: { style: 'color;background;width: 120px' }, children: [ 'hey' ] }\n" +
" // Expectation contains invalid styles: 'color;background'\n" +
'>hey</div>'
);
});

it('should fail when the subject is missing an inline style', function() {
return expect(
function() {
Expand Down

0 comments on commit 1d568a7

Please sign in to comment.