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

Fix: Validate style attributes on the RHS #222

Merged
merged 1 commit into from
Oct 26, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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