Skip to content

Commit

Permalink
fix(prefer-to-have-style): handle regexp literals
Browse files Browse the repository at this point in the history
  • Loading branch information
G-Rath committed May 20, 2022
1 parent 186ae50 commit 8f39db1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
5 changes: 5 additions & 0 deletions src/__tests__/lib/rules/prefer-to-have-style.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ ruleTester.run("prefer-to-have-style", rule, {
`expect(el.style).toEqual(foo)`,
`expect(el.style[1]).toEqual([])`,
`expect(el.style[1]).toEqual({})`,
`expect(element.style[0]).toBe(new RegExp('reg'));`,
`expect(el).toHaveAttribute("style")`,
`React.useLayoutEffect(() => {
if (foo) {
Expand Down Expand Up @@ -162,5 +163,9 @@ ruleTester.run("prefer-to-have-style", rule, {
code: `expect(element.style[0]).toBe(1);`,
errors,
},
{
code: `expect(element.style[0]).toBe(/RegExp/);`,
errors,
},
],
});
23 changes: 12 additions & 11 deletions src/rules/prefer-to-have-style.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,10 @@ export const create = (context) => {

let fix = null;

if (typeof styleValue.value !== "number") {
if (
typeof styleValue.value !== "number" &&
!(styleValue.value instanceof RegExp)
) {
fix = (fixer) => {
return [
fixer.removeRange([
Expand Down Expand Up @@ -249,9 +252,9 @@ export const create = (context) => {
fixer.replaceText(matcher, "toHaveStyle"),
fixer.replaceTextRange(
[styleName.range[0], styleValue.range[1]],
`{${camelCase(
styleName.value
)}: ${context.getSourceCode().getText(styleValue)}}`
`{${camelCase(styleName.value)}: ${context
.getSourceCode()
.getText(styleValue)}}`
),
];
},
Expand All @@ -262,10 +265,8 @@ export const create = (context) => {
[`MemberExpression[property.name=style][parent.parent.property.name=not][parent.parent.parent.property.name=toHaveProperty][parent.callee.name=expect]`](
node
) {
const [
styleName,
styleValue,
] = node.parent.parent.parent.parent.arguments;
const [styleName, styleValue] =
node.parent.parent.parent.parent.arguments;
const matcher = node.parent.parent.parent.property;

context.report({
Expand All @@ -283,9 +284,9 @@ export const create = (context) => {
fixer.replaceText(matcher, "toHaveStyle"),
fixer.replaceTextRange(
[styleName.range[0], styleValue.range[1]],
`{${camelCase(
styleName.value
)}: ${context.getSourceCode().getText(styleValue)}}`
`{${camelCase(styleName.value)}: ${context
.getSourceCode()
.getText(styleValue)}}`
),
];
},
Expand Down

0 comments on commit 8f39db1

Please sign in to comment.