diff --git a/crates/swc/tests/fixture/jest/issue-6540/input/.swcrc b/crates/swc/tests/fixture/jest/issue-6540/input/.swcrc new file mode 100644 index 000000000000..bd05168a3372 --- /dev/null +++ b/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" + } +} \ No newline at end of file diff --git a/crates/swc/tests/fixture/jest/issue-6540/input/index.ts b/crates/swc/tests/fixture/jest/issue-6540/input/index.ts new file mode 100644 index 000000000000..fcab80309297 --- /dev/null +++ b/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); +}); diff --git a/crates/swc/tests/fixture/jest/issue-6540/output/index.ts b/crates/swc/tests/fixture/jest/issue-6540/output/index.ts new file mode 100644 index 000000000000..38cbeb94c1ac --- /dev/null +++ b/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); +}); diff --git a/crates/swc_ecma_ext_transforms/src/jest.rs b/crates/swc_ecma_ext_transforms/src/jest.rs index 66af9e62bb80..7d3bed7f8b9c 100644 --- a/crates/swc_ecma_ext_transforms/src/jest.rs +++ b/crates/swc_ecma_ext_transforms/src/jest.rs @@ -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)), @@ -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, + } +}