Skip to content

Commit

Permalink
fix(class-to-function): Fixed conversion of class properties with fun…
Browse files Browse the repository at this point in the history
…ction value. Fixes #95
  • Loading branch information
borislit committed Mar 19, 2021
1 parent c2a7411 commit e5177a1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/modules/stateful-to-stateless.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export function statefulToStateless(component) {
if (
t.isIdentifier(path.node.property) &&
t.isThisExpression(path.node.object) &&
!classMethods.has(path.node.property.name) &&
!classMethods.has(path.node.property.name) &&
path.node.property.name !== 'props'
) {
if (!refProperties.has(path.node.property.name)) {
Expand Down Expand Up @@ -325,6 +325,7 @@ export function statefulToStateless(component) {
t.isFunctionExpression(propValue) ||
t.isArrowFunctionExpression(propValue)
) {
classMethods.add(path.node.key.name);
copyNonLifeCycleMethods(path);
} else {
refProperties.set(path.node.key.name, path.node.value);
Expand Down
27 changes: 27 additions & 0 deletions src/test/class-to-functional.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,33 @@ describe("when refactoring stateful component into stateless component", () => {
);
});

it("treats class properties with function experession as a class method when converting", async () => {
givenApprovedWarning();
sandbox.stub(editor, "selectedText").returns(`
class SomeComponent extends React.Component {
doFoo = () => {
console.log(2);
}
render() {
return (
<div>
{this.state.foo} + {this.state.bar}
</div>
);
}
}
`);

await statefulToStatelessComponent();

expect(fileSystem.replaceTextInFile).to.have.been.calledWith(
"const SomeComponent = props => {\n const [foo, setFoo] = useState();\n const [bar, setBar] = useState();\n const doFoo = useCallback(() => {\n console.log(2);\n });\n return <div>\n {foo} + {bar}\n </div>;\n};",
selectedTextStart,
selectedTextEnd,
"/source.js"
);
});

it("replaces componentWillUnmount with useEffect cleanup function", async () => {
givenApprovedWarning();
sandbox.stub(editor, "selectedText").returns(`
Expand Down

0 comments on commit e5177a1

Please sign in to comment.