Skip to content

Commit

Permalink
feat(es/jest): Support chaining of jest function calls (#6747)
Browse files Browse the repository at this point in the history
**Related issue:**

 - Closes #6540.
  • Loading branch information
kdy1 committed Jan 4, 2023
1 parent 1638105 commit 72fb606
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 6 deletions.
23 changes: 23 additions & 0 deletions crates/swc/tests/fixture/jest/issue-6540/input/.swcrc
@@ -0,0 +1,23 @@
{
"jsc": {
"parser": {
"syntax": "typescript",
"tsx": false,
"dynamicImport": true,
"decorators": true
},
"transform": {
"legacyDecorator": true,
"hidden": {
"jest": true
}
},
"target": "es2016",
"loose": false,
"externalHelpers": false,
"keepClassNames": false
},
"module": {
"type": "commonjs"
}
}
7 changes: 7 additions & 0 deletions crates/swc/tests/fixture/jest/issue-6540/input/index.ts
@@ -0,0 +1,7 @@
import foo from "./foo";

jest.mock("./foo").mock("./bar");

test("Foo is a mock", () => {
expect(jest.isMockFunction(foo)).toBe(true);
});
10 changes: 10 additions & 0 deletions crates/swc/tests/fixture/jest/issue-6540/output/index.ts
@@ -0,0 +1,10 @@
"use strict";
jest.mock("./foo").mock("./bar");
Object.defineProperty(exports, "__esModule", {
value: true
});
const _interopRequireDefault = require("@swc/helpers/lib/_interop_require_default.js").default;
const _foo = /*#__PURE__*/ _interopRequireDefault(require("./foo"));
test("Foo is a mock", ()=>{
expect(jest.isMockFunction(_foo.default)).toBe(true);
});
23 changes: 17 additions & 6 deletions crates/swc_ecma_ext_transforms/src/jest.rs
Expand Up @@ -44,14 +44,13 @@ impl Jest {
prop: MemberProp::Ident(prop),
..
},
) => match &*callee.obj {
Expr::Ident(i)
if i.sym == *"jest" && HOIST_METHODS.contains(&*prop.sym) =>
{
) => {
if is_jest(&callee.obj) && HOIST_METHODS.contains(&*prop.sym) {
hoisted.push(T::from_stmt(stmt))
} else {
new.push(T::from_stmt(stmt));
}
_ => new.push(T::from_stmt(stmt)),
},
}
_ => new.push(T::from_stmt(stmt)),
},
_ => new.push(T::from_stmt(stmt)),
Expand Down Expand Up @@ -80,3 +79,15 @@ impl VisitMut for Jest {
self.visit_mut_stmt_like(stmts)
}
}

fn is_jest(e: &Expr) -> bool {
match e {
Expr::Ident(i) => i.sym == *"jest",
Expr::Member(MemberExpr { obj, .. }) => is_jest(obj),
Expr::Call(CallExpr {
callee: Callee::Expr(callee),
..
}) => is_jest(callee),
_ => false,
}
}

0 comments on commit 72fb606

Please sign in to comment.